﻿(function ($) {
    // 继承方法
    Function.prototype.eiapExtend = function (parent, overrides) {
        if (typeof parent != 'function')
            return this;
        // 保存对父类的引用
        this.base = parent.prototype;
        this.base.constructor = parent;
        // 继承
        var f = function () {
        };
        f.prototype = parent.prototype;
        this.prototype = new f();
        this.prototype.constructor = this;
        // 附加属性方法
        if (overrides)
            $.extend(this.prototype, overrides);
    };
    // 延时加载
    Function.prototype.eiapDefer = function (o, defer, args) {
        var fn = this;
        return setTimeout(function () {
            fn.apply(o, args || []);
        }, defer);
    };

    $(window).bind("resize", function () {
        var newWidth = $(window).width();
        var newHeight = $(window).height();
        if (EIAP.wWidth != newWidth || EIAP.wHeight != newHeight) {
            var wRatio = newWidth / EIAP.wWidth;
            var hRatio = newHeight / EIAP.wHeight;
            EIAP.wWidth = newWidth;
            EIAP.wHeight = newHeight;
            EIAP.resizeAll(wRatio, hRatio);
        }
    });
    window.EIAP = $.eiapui = {
        version: 'v2.6.4.001',
        namespace: function () {
            var o, d, s;
            for (var i = 0; i < arguments.length; i++) {
                d = arguments[i].split(".");
                o = window[d[0]] = window[d[0]] || {};
                s = d.slice(1);
                for (var m = 0; m < s.length; m++) {
                    o = o[s[m]] = o[s[m]] || {};
                }
            }
            return o;
        },
        isIE: $.browser.msie ? true : false,
        wHeight: $(window).height(),
        wWidth: $(window).width(),
        BLANK_IMAGE_URL: 'http://' + window.location.host + '/EIAP/resources/images/s.gif',
        managerCount: 0,
        managers: {},
        wmanagers: [],
        topCmps: {},
        managerIdPrev: 'eiapui',
        isDefined: function (v) {
            return typeof v !== 'undefined';
        },
        applyIf: function (o, c) {
            if (o) {
                for (var p in c) {
                    if (!EIAP.isDefined(o[p])) {
                        o[p] = c[p];
                    }
                }
            }
            return o;
        },
        apply: function (o, c, defaults) {
            if (defaults) {
                EIAP.apply(o, defaults);
            }
            if (o && c && typeof c == 'object') {
                for (var p in c) {
                    o[p] = c[p];
                }
            }
            return o;
        },
        applyHave: function (o, c) {
            if (o && c && typeof c == 'object') {
                for (var p in o) {
                    if (c[p] != undefined && c[p] != null)
                        o[p] = c[p];
                }
            }
            return o;
        },
        override: function (origclass, overrides) {
            if (overrides) {
                var p = origclass.prototype;
                EIAP.apply(p, overrides);
                if (overrides.hasOwnProperty('toString')) {
                    p.toString = overrides.toString;
                }
            }
        },
        extend: function () {
            // inline overrides
            var io = function (o) {
                for (var m in o) {
                    this[m] = o[m];
                }
            };
            var oc = Object.prototype.constructor;

            return function (sb, sp, overrides) {
                if (typeof sp == 'object') {
                    overrides = sp;
                    sp = sb;
                    sb = overrides.constructor != oc
                        ? overrides.constructor
                        : function () {
                            sp.apply(this, arguments);
                        };
                }
                var F = function () {
                }, sbp, spp = sp.prototype;

                F.prototype = spp;
                sbp = sb.prototype = new F();
                sbp.constructor = sb;
                sb.superclass = spp;
                if (spp.constructor == oc) {
                    spp.constructor = sp;
                }
                sb.override = function (o) {
                    EIAP.override(sb, o);
                };
                sbp.superclass = sbp.supr = (function () {
                    return spp;
                });
                sbp.override = io;
                EIAP.override(sb, overrides);
                sb.extend = function (o) {
                    return EIAP.extend(sb, o);
                };
                return sb;
            };
        }(),
        getBody: function () {
            return $("body");
        },
        getId: function (prev) {
            prev = prev || this.managerIdPrev;
            var id = prev + (1000 + this.managerCount);
            this.managerCount++;
            return id;
        },
        add: function (cmp) {
            if (!cmp.id)
                cmp.id = this.getId(cmp.__idPrev());
            if (this.managers[cmp.id]) {
                throw new Error(this.error.managerIsExist + "[" + cmp.id + "]");
            }
            this.managers[cmp.id] = cmp;
            if (cmp.type == "Window") {
                cmp.index = this.wmanagers.length;
                this.wmanagers.push(cmp);
            }
        },
        remove: function (arg) {
            var cmp = null;
            if (typeof arg == "string") {
                cmp = this.managers[arg];
            } else if (typeof arg == "object"
                && arg instanceof $.eiapui.core.Component) {
                cmp = this.managers[arg.id];
            }
            if (cmp) {
                if (cmp.items) {
                    for (var i = 0; i < cmp.items.length; i++) {
                        this.remove(EIAP.getCmp(cmp.items[i]));
                    }
                }
                cmp.remove && cmp.remove();
                cmp.element && $(cmp.element).remove();
                cmp.dom && cmp.dom.remove();
                delete this.managers[cmp.id];
            }

        },
        get: function (arg, idAttrName) {
            idAttrName = idAttrName || "eiapuiid";
            if (typeof arg == "string" || typeof arg == "number") {
                return $.eiapui.managers[arg];
            } else if (arg && typeof arg == "object" && arg.length) {
                if (!arg[0][idAttrName] && !$(arg[0]).attr(idAttrName))
                    return null;
                return $.eiapui.managers[arg[0][idAttrName]
                    || $(arg[0]).attr(idAttrName)];
            }
            return null;
        },
        getCmp: function () {
            return EIAP.managers[arguments[0]];
        },
        find: function (type) {
            var arr = [];
            for (var id in this.managers) {
                var manager = this.managers[id];
                if (type instanceof Function) {
                    if (manager instanceof type) {
                        arr.push(manager);
                    }
                } else if (type instanceof Array) {
                    if ($.inArray(manager.__getType(), type) != -1) {
                        arr.push(manager);
                    }
                } else {
                    if (manager.__getType() == type) {
                        arr.push(manager);
                    }
                }
            }
            return arr;
        },
        resizeAll: function () {
            var cmps = EIAP.managers;
            for (var cmp in cmps) {
                if (cmps[cmp] || cmps[cmp].type == "Window" && cmps[cmp].ismax === true) {
                    cmps[cmp].onResize();
                }
            }
            //            var cmps = EIAP.topCmps;
            //            for (var cmp in cmps) {
            //                if (cmps[cmp]) {
            //                    this.resize(cmps[cmp]);
            //                }
            //            }
        },
        resize: function () {
            var cmp = arguments[0];
            cmp.onResize();
            if (cmp.items) {
                for (var i = 0; i < cmp.items.length; i++)
                    EIAP.resize(EIAP.getCmp(cmp.items[i]));
            }
        },
        toArray: function () {
            return $.browser.msie ?
                function (a, i, j, res) {
                    res = [];
                    for (var x = 0, len = a.length; x < len; x++) {
                        res.push(a[x]);
                    }
                    return res.slice(i || 0, j || res.length);
                } :
                function (a, i, j) {
                    return Array.prototype.slice.call(a, i || 0, j || a.length);
                };
        }(),
        isJsonObj: function (obj) {
            return typeof (obj) == "object" && Object.prototype.toString.call(obj).toLowerCase() == "[object object]" && !obj.length;
        },
        onReady: function () {
            if (arguments)
                $(window).load(arguments[0]);
        },
        importJs: function (js, fn, cache) {
            var fnJs = function (j, f, c, num, sum) {
                $.ajax({
                    url: j[num],
                    dataType: "script",
                    cache: c == undefined ? true : false,
                    success: function (e) {
                        if (num == (sum - 1)) {
                            f.call(f, e);
                        } else {
                            num++;
                            fnJs(j, f, c, num, sum);
                        }
                    }
                });
            };
            if (js instanceof Array) {
                fnJs(js, fn, cache, 0, js.length);
            } else {
                fnJs([js], fn, cache, 0, 1);
            }
        }
    };
    EIAP.ns = EIAP.namespace;
    EIAP.ns("EIAP.core", "EIAP.util", "EIAP.panel", "EIAP.grid", "EIAP.tree", "EIAP.form", "EIAP.layout", "EIAP.tab", "EIAP.menu", "EIAP.toolbar", "EIAP.button", "EIAP.window", "EIAP.controls", "EIAP.widgets", "EIAP.data", "EIAP.shadow", "EIAP.calendar");
    EIAP.apply(Function.prototype, {
        createCallback: function () {
            var args = arguments, method = this;
            return function () {
                return method.apply(window, args);
            };
        }
    });
    EIAP.applyIf(String, {
        format: function (format) {
            var args = EIAP.toArray(arguments, 1);
            return format.replace(/\{(\d+)\}/g, function (m, i) {
                return args[i];
            });
        }
    });

    // 组件基类
    // 1,完成定义参数处理方法和参数属性初始化的工作
    // 2,完成定义事件处理方法和事件属性初始化的工作
    EIAP.Component = $.eiapui.core.Component = function (options) {
        // 事件容器
        this.events = this.events || {};
        // 配置参数
        this.options = options || {};
        // 子组件集合索引
        this.items = null;
        // 初始化id
        if (!options || (!options.id && !options.renderTo)) {
            this.id = $.eiapui.getId(this.__idPrev());
        } else {
            this.id = options.id ? options.id : options.renderTo;
        }
    };
    $.extend($.eiapui.core.Component.prototype, {
        __getType: function () {
            return '$.eiapui.core.Component';
        },
        __idPrev: function () {
            return 'eiapui';
        },
        // 设置属性
        // arg 属性名 value 属性值
        // arg 属性/值 value 是否只设置事件
        set: function (arg, value) {
            var g = this;
            if (!arg)
                return;
            if (typeof arg == 'object') {
                var tmp;
                if (g != arg) {
                    $.extend(g, arg);
                    tmp = arg;
                } else {
                    tmp = $.extend({}, arg);
                }
                if (value == undefined || value == true) {
                    for (var p in tmp) {
                        if (p.indexOf('on') == 0)
                            g.set(p, tmp[p]);
                    }
                }
                if (value == undefined || value == false) {
                    for (var p in tmp) {
                        if (p.indexOf('on') != 0)
                            g.set(p, tmp[p]);
                    }
                }
                return;
            }
            var name = arg;
            // 事件参数
            if (name.indexOf('on') == 0) {
                if (typeof value == 'function')
                    g.bind(name.substr(2), value);
                return;
            }
            g.trigger('propertychange', arg, value);
            g[name] = value;
            var pn = '_set' + name.substr(0, 1).toUpperCase()
							+ name.substr(1);
            if (g[pn]) {
                g[pn].call(g, value);
            }
            g.trigger('propertychanged', arg, value);
        },

        // 获取属性
        get: function (name) {
            var pn = '_get' + name.substr(0, 1).toUpperCase()
							+ name.substr(1);
            if (this[pn]) {
                return this[pn].call(this, name);
            }
            return this.options[name];
        },

        hasBind: function (arg) {
            var name = arg.toLowerCase();
            var event = this.events[name];
            if (event && event.length)
                return true;
            return false;
        },

        // 触发事件
        // data (可选) Array(可选)传递给事件处理函数的附加参数
        trigger: function (arg, data) {
            var name = arg.toLowerCase();
            var event = this.events[name];
            if (!event)
                return;
            data = data || [];
            if ((data instanceof Array) == false) {
                data = [data];
            }
            for (var i = 0; i < event.length; i++) {
                var ev = event[i];
                if (ev.handler.apply(ev.context, data) == false)
                    return false;
            }
        },
        fireEvent: function () {
            var evt = arguments[0];
            var a = Array.prototype.slice.call(arguments, 1);
            if (this.events[evt]) {
                for (var i = 0; i < this.events[evt].length; i++) {
                    if (this.events[evt][i].apply(this, [a[0]]) == false) {
                        return false;
                    }
                }
            }
        },
        on: function () {
            var evts = arguments[0];
            var evtFn = arguments[1];
            if (typeof evts == 'object') {
                for (var p in evts) {
                    if (this.events[p]) {
                        this.events[p].push(evts[p]);
                    } else {
                        this.events[p] = [evts[p]];
                    }
                }
            } else {
                if (this.events[evts]) {
                    this.events[evts].push(evtFn);
                } else {
                    this.events[evts] = [evtFn];
                }
            }
        },
        un: function () {
            var evts = arguments[0];
            var evtFn = arguments[1];
            var i = 0, fn;
            if (typeof events == 'object') {
                for (var p in evts) {
                    if (this.events[p]) {
                        for (i = 0; i < this.events[p].length; i++) {
                            fn = this.events[p][i];
                            if (fn == evts[p]) {
                                this.events[p].splice(i, 1);
                                return;
                            }
                        }
                    }
                }
            } else {
                if (this.events[evts]) {
                    for (i = 0; i < this.events[evts].length; i++) {
                        fn = this.events[evts][i];
                        if (fn == evtFn) {
                            this.events[evts].splice(i, 1);
                            return;
                        }
                    }
                }
            }
        },
        // 绑定事件
        bind: function (arg, handler, context) {
            if (typeof arg == 'object') {
                for (var p in arg) {
                    this.bind(p, arg[p]);
                }
                return;
            }
            if (typeof handler != 'function')
                return false;
            var name = arg.toLowerCase();
            var event = this.events[name] || [];
            context = context || this;
            event.push({
                handler: handler,
                context: context
            });
            this.events[name] = event;
        },

        // 取消绑定
        unbind: function (arg, handler) {
            if (!arg) {
                this.events = {};
                return;
            }
            var name = arg.toLowerCase();
            var event = this.events[name];
            if (!event || !event.length)
                return;
            if (!handler) {
                delete this.events[name];
            } else {
                for (var i = 0, l = event.length; i < l; i++) {
                    if (event[i].handler == handler) {
                        event.splice(i, 1);
                        break;
                    }
                }
            }
        },
        destroy: function () {
            $.eiapui.remove(this);
        }
    });
    // 界面组件基类,
    // 1,完成界面初始化:设置组件id并存入组件管理器池,初始化参数
    // 2,渲染的工作,细节交给子类实现
    // @parm [options] 组件的参数
    EIAP.UIComponent = $.eiapui.core.UIComponent = function () {
        EIAP.apply(this, arguments[0]);
        EIAP.UIComponent.superclass.constructor.call(this, arguments[0]);
        this.initComponent();
        this.run();
        if (this.hidden && this.dom) {
            this.dom.hide();
        }
        return this;
    };
    EIAP.extend(EIAP.UIComponent, EIAP.Component, {
        doInit: function () {
            var extMethods = this._extMethods();
            if (extMethods)
                $.extend(this, extMethods);
            this.element = arguments[0];
            this._init();
            this._preRender();
            this.trigger('render');
            this._render();
            this.addItems();
            this.trigger('rendered');
            this._rendered();
        },
        show: function () {
            this.dom && this.dom.show();
        },
        hide: function () {
            this.dom && this.dom.hide();
        },
        run: function () {
            var curthis = this, args = [this.options];
            var dom = curthis.options.renderTo ? $("#" + curthis.options.renderTo) : window;
            var widget = curthis.__getType();
            if (!widget)
                return;
            var ext = $.extend({
                idAttrName: 'eiapuiid',
                isStatic: false,
                hasElement: true, // 是否拥有element主体(比如drag、resizable等辅助性插件就不拥有)
                propertyToElemnt: null
                // 链接到element的属性名
            }, arguments[0] || {});
            if (dom == null || dom == window || ext.isStatic) {
                if (!$.eiapui.widgets[widget]) {
                    $.eiapui.widgets[widget] = {
                        fn: $['eiap' + widget],
                        isStatic: true
                    };
                }
                return curthis.doInit();
            }
            if (!$.eiapui.widgets[widget]) {
                $.eiapui.widgets[widget] = {
                    fn: $.fn['eiap' + widget],
                    isStatic: false
                };
            }
            if (/Manager$/.test(widget))
                return $.eiapui.get(dom, ext.idAttrName);
            dom.each(function () {
                if (this[ext.idAttrName]
										|| $(widget).attr(ext.idAttrName)) {
                    var manager = $.eiapui
											.get(this[ext.idAttrName]
													|| $(this)
															.attr(ext.idAttrName));
                    if (manager && args.length > 0)
                        manager.set(args[0]);
                    // 已经执行过
                    return;
                }
                if (args.length >= 1
										&& typeof args[0] == 'string')
                    return;
                // 只要第一个参数不是string类型,都执行组件的实例化工作
                var options = args.length > 0 ? args[0] : null;
                var p = $.extend({}, options || {});
                if (ext.propertyToElemnt)
                    p[ext.propertyToElemnt] = this;
                if (ext.hasElement) {
                    curthis.doInit(this);
                } else {
                    curthis.doInit();
                }
            });
            if (curthis.length == 0)
                return null;
            if (args.length == 0)
                return $.eiapui.get(dom, ext.idAttrName);
            if (typeof args[0] == 'object')
                return $.eiapui.get(dom, ext.idAttrName);
            if (typeof args[0] == 'string') {
                var manager = $.eiapui.get(curthis, ext.idAttrName);
                if (manager == null)
                    return;
                if (args[0] == "option") {
                    if (args.length == 2)
                        return manager.get(args[1]); // manager get
                    else if (args.length >= 3)
                        return manager.set(args[1], args[2]); // manager
                    // set
                } else {
                    var method = args[0];
                    if (!manager[method])
                        return; // 不存在这个方法
                    var parms = Array.apply(null, args);
                    parms.shift();
                    return manager[method].apply(manager, parms); // manager
                    // method
                }
            }
            return null;
        },
        initComponent: function () {
            var items = this.options.items;
            this.items = [];
            if (items) {
                for (var i = 0; i < items.length; i++) {
                    items[i].parentCmp = this.id;
                    items[i].isDefined = true;
                }
            }
        },
        addItems: function () {
            var items = this.options.items;
            if (items) {
                for (var i = 0; i < items.length; i++) {
                    var item = items[i];
                    var xtype = item.xtype ? item.xtype : this.defaultType;
                    EIAP.applyIf(item, this.defaultStyle);
                    if (!xtype) {
                        throw new Error(EIAP.error.noXtype);
                    }
                    var cmp = eval("EIAP." + xtype);
                    if (!cmp) {
                        throw new Error(String.format(EIAP.error.noCmp, xtype));
                    }
                    cmp = cmp.call(cmp, item);
                    this.items.push(cmp.id);
                }
            }
        },

        __getType: function () {
            return '$.eiapui.core.UIComponent';
        },
        // 扩展方法
        _extMethods: function () {

        },
        _init: function () {
            this.type = this.__getType();

            // 存入管理器池
            $.eiapui.add(this);

            if (!this.element)
                return;

            // 读取attr方法,并加载到参数,比如['url']
            var attributes = this.attr();
            if (attributes && attributes instanceof Array) {
                for (var i = 0; i < attributes.length; i++) {
                    var name = attributes[i];
                    this[name] = $(this.element).attr(name);
                }
            }
            // 读取eiapui这个属性，并加载到参数，比如 eiapui = "width:120,heigth:100"
            if ($(this.element).attr("eiapui")) {
                try {
                    var attroptions = $(this.element).attr("eiapui");
                    if (attroptions.indexOf('{') != 0)
                        attroptions = "{" + attroptions + "}";
                    eval("attroptions = " + attroptions + ";");
                    if (attroptions)
                        $.extend(this, attroptions);
                } catch (e) {
                }
            }
        },
        // 预渲染,可以用于继承扩展
        _preRender: function () {

        },
        _render: function () {

        },
        _rendered: function () {
            if (this.element) {
                $(this.element).attr("eiapuiid", this.id);
            } else {
                this.dom.attr("eiapuiid", this.id);
            }
        },
        // 返回要转换成eiapui参数的属性,比如['url']
        attr: function () {
            return [];
        },
        addItem: function (cmp) {
            cmp.parentCmp = this.id;
            cmp.isDefined = true;
            this.items.push(cmp.id);
            var dom = this.getDom();
            dom.append(cmp.dom);
        },
        insertItem: function (cmp, index) {
            if (typeof index == "number" && index >= 0 && index < this.items.length) {
                cmp.parentCmp = this.id;
                cmp.isDefined = true;
                var num = 0;
                for (var i = 0; i < this.items.length; i++) {
                    var item = EIAP.getCmp(this.items[i]);
                    if (item.isDefined) {
                        if (num == index) {
                            this.items.slice(cmp, 0, i + 1);
                            var dom = item.getDom();
                            dom.after(cmp.dom);
                            return;
                        }
                        num++;
                    }
                }
            }
        },
        getDom: function () {
            return this.dom;
        },
        onResize: function () {
        },
        addToTop: function () {
            var parent = this.dom ? this.dom.parent() : null;
            if (this.type != "Window" && parent && parent[0] && parent[0].tagName.toLowerCase() == "body") {
                if (!EIAP.topCmps[this.id])
                    EIAP.topCmps[this.id] = this;
            }
        }
    });
    EIAP.draggable = {
        dragging: false
    };
    EIAP.resizable = {
        reszing: false
    };

    EIAP.CustomUI = function () {
        EIAP.apply(this, arguments[0]);
        this.initComponent();
        return this;
    };
    EIAP.CustomUI.prototype = {
        initComponent: function () {

        }
    };
})(jQuery);﻿(function() {
    // Establish the object that gets returned to break out of a loop iteration.
    var breaker = {};

    // Save bytes in the minified (but not gzipped) version:
    var arrayProto = Array.prototype;

    // Create quick reference variables for speed access to core prototypes.
    var slice = arrayProto.slice,
        concat = arrayProto.concat;

    // All **ECMAScript 5** native function implementations that we hope to use
    // are declared here.
    var nativeForEach = arrayProto.forEach,
        nativeMap = arrayProto.map,
        nativeFilter = arrayProto.filter,
        nativeEvery = arrayProto.every,
        nativeSome = arrayProto.some,
        nativeIndexOf = arrayProto.indexOf,
        nativeLastIndexOf = arrayProto.lastIndexOf;

    // Keep the identity function around for default iterators.
    var identity = function(value) {
        return value;
    };


    // An internal function to generate lookup iterators.
    var lookupIterator = function(value) {
        return EIAP.util.Obj.isFunction(value) ? value : function(obj) { return obj[value]; };
    };

    // An internal function used for aggregate "group by" operations.
    var group = function(obj, value, context, behavior) {
        var result = {};
        var iterator = lookupIterator(value || identity);
        EIAP.util.Array.each(obj, function (innerValue, index) {
            var key = iterator.call(context, innerValue, index, obj);
            behavior(result, key, innerValue);
        });
        return result;
    };


    EIAP.util.Array = {
        // The cornerstone, an `each` implementation, aka `forEach`.
        // Handles objects with the built-in `forEach`, arrays, and raw objects.
        // Delegates to **ECMAScript 5**'s native `forEach` if available.
        each: function(obj, iterator, context) {
            if (obj == null) return;
            if (nativeForEach && obj.forEach === nativeForEach) {
                obj.forEach(iterator, context);
            } else if (obj.length === +obj.length) {
                for (var i = 0, l = obj.length; i < l; i++) {
                    if (iterator.call(context, obj[i], i, obj) === breaker) return;
                }
            } else {
                for (var key in obj) {
                    if (EIAP.util.Obj.has(obj, key)) {
                        if (iterator.call(context, obj[key], key, obj) === breaker) return;
                    }
                }
            }
        },
        // Determine if at least one element in the object matches a truth test.
        // Delegates to **ECMAScript 5**'s native `some` if available.
        // Aliased as `any`.
        any: function (obj, iterator, context) {
            iterator || (iterator = identity);
            var result = false;
            if (obj == null) return result;
            if (nativeSome && obj.some === nativeSome) return obj.some(iterator, context);
            this.each(obj, function (value, index, list) {
                if (result || (result = iterator.call(context, value, index, list))) return breaker;
            });
            return !!result;
        },
        // Return the results of applying the iterator to each element.
        // Delegates to **ECMAScript 5**'s native `map` if available.
        map: function(obj, iterator, context) {
            var results = [];
            if (obj == null) return results;
            if (nativeMap && obj.map === nativeMap) return obj.map(iterator, context);
            this.each(obj, function(value, index, list) {
                results[results.length] = iterator.call(context, value, index, list);
            });
            return results;
        },
        // Return the first value which passes a truth test. Aliased as `detect`.
        find: function(obj, iterator, context) {
            var result;
            this.any(obj, function(value, index, list) {
                if (iterator.call(context, value, index, list)) {
                    result = value;
                    return true;
                }
            });
            return result;
        },
        // Return all the elements that pass a truth test.
        // Delegates to **ECMAScript 5**'s native `filter` if available.
        // Aliased as `select`.
        filter: function(obj, iterator, context) {
            var results = [];
            if (obj == null) return results;
            if (nativeFilter && obj.filter === nativeFilter) return obj.filter(iterator, context);
            this.each(obj, function(value, index, list) {
                if (iterator.call(context, value, index, list)) results[results.length] = value;
            });
            return results;
        },
        // Return all the elements for which a truth test fails.
        reject: function(obj, iterator, context) {
            return this.filter(obj, function(value, index, list) {
                return !iterator.call(context, value, index, list);
            }, context);
        },
        // Determine whether all of the elements match a truth test.
        // Delegates to **ECMAScript 5**'s native `every` if available.
        // Aliased as `all`.
        every: function(obj, iterator, context) {
            iterator || (iterator = identity);
            var result = true;
            if (obj == null) return result;
            if (nativeEvery && obj.every === nativeEvery) return obj.every(iterator, context);
            this.each(obj, function(value, index, list) {
                if (!(result = result && iterator.call(context, value, index, list))) return breaker;
            });
            return !!result;
        },
        // Determine if the array or object contains a given value (using `===`).
        // Aliased as `include`.
        contains: function(obj, target) {
            if (obj == null) return false;
            if (nativeIndexOf && obj.indexOf === nativeIndexOf) return obj.indexOf(target) != -1;
            return this.any(obj, function(value) {
                return value === target;
            });
        },
        // Invoke a method (with arguments) on every item in a collection.
        invoke: function(obj, method) {
            var args = slice.call(arguments, 2);
            var isFunc = EIAP.util.Obj.isFunction(method);
            return this.map(obj, function(value) {
                return (isFunc ? method : value[method]).apply(value, args);
            });
        },
        // Convenience version of a common use case of `map`: fetching a property.
        pluck: function(obj, key) {
            return this.map(obj, function(value) { return value[key]; });
        },
        // Convenience version of a common use case of `filter`: selecting only objects
        // containing specific `key:value` pairs.
        where: function(obj, attrs, first) {
            if (EIAP.util.Obj.isEmpty(attrs)) return first ? null : [];
            return this[first ? 'find' : 'filter'](obj, function (value) {
                for (var key in attrs) {
                    if (attrs[key] !== value[key]) return false;
                }
                return true;
            });
        },
        // Convenience version of a common use case of `find`: getting the first object
        // containing specific `key:value` pairs.
        findWhere: function(obj, attrs) {
            return this.where(obj, attrs, true);
        },

        // Return the maximum element or (element-based computation).
        // Can't optimize arrays of integers longer than 65,535 elements.
        // See: https://bugs.webkit.org/show_bug.cgi?id=80797
        max: function(obj, iterator, context) {
            if (!iterator && EIAP.util.Obj.isArray(obj) && obj[0] === +obj[0] && obj.length < 65535) {
                return Math.max.apply(Math, obj);
            }
            if (!iterator && EIAP.util.Obj.isEmpty(obj)) return -Infinity;
            var result = { computed: -Infinity, value: -Infinity };
            this.each(obj, function(value, index, list) {
                var computed = iterator ? iterator.call(context, value, index, list) : value;
                computed >= result.computed && (result = { value: value, computed: computed });
            });
            return result.value;
        },
        // Return the minimum element (or element-based computation).
        min: function(obj, iterator, context) {
            if (!iterator && EIAP.util.Obj.isArray(obj) && obj[0] === +obj[0] && obj.length < 65535) {
                return Math.min.apply(Math, obj);
            }
            if (!iterator && EIAP.util.Obj.isEmpty(obj)) return Infinity;
            var result = { computed: Infinity, value: Infinity };
            this.each(obj, function(value, index, list) {
                var computed = iterator ? iterator.call(context, value, index, list) : value;
                computed < result.computed && (result = { value: value, computed: computed });
            });
            return result.value;
        },
        // Shuffle an array.
        shuffle: function(obj) {
            var rand;
            var index = 0;
            var shuffled = [];
            this.each(obj, function(value) {
                rand = EIAP.util.Math.random(index++);
                shuffled[index - 1] = shuffled[rand];
                shuffled[rand] = value;
            });
            return shuffled;
        },
        // Sort the object's values by a criterion produced by an iterator.
        sortBy: function(obj, value, context) {
            var iterator = lookupIterator(value);
            return this.pluck(this.map(obj, function(innerValue, index, list) {
                return {
                    value: innerValue,
                    index: index,
                    criteria: iterator.call(context, innerValue, index, list)
                };
            }).sort(function(left, right) {
                var a = left.criteria;
                var b = right.criteria;
                if (a !== b) {
                    if (a > b || a === void 0) return 1;
                    if (a < b || b === void 0) return -1;
                }
                return left.index < right.index ? -1 : 1;
            }), 'value');
        },
        // Groups the object's values by a criterion. Pass either a string attribute
        // to group by, or a function that returns the criterion.
        groupBy: function(obj, value, context) {
            return group(obj, value, context, function(result, key, innerValue) {
                (EIAP.util.Obj.has(result, key) ? result[key] : (result[key] = [])).push(innerValue);
            });
        },
        // Counts instances of an object that group by a certain criterion. Pass
        // either a string attribute to count by, or a function that returns the
        // criterion.
        countBy: function(obj, value, context) {
            return group(obj, value, context, function(result, key) {
                if (EIAP.util.Obj.has(result, key)) result[key] = 0;
                result[key]++;
            });
        },
        // Safely convert anything iterable into a real, live array.
        toArray: function(obj) {
            if (!obj) return [];
            if (EIAP.util.Obj.isArray(obj)) return slice.call(obj);
            if (obj.length === +obj.length) return this.map(obj, identity);
            return EIAP.util.Obj.values(obj);
        },
        // Return the number of elements in an object.
        size: function(obj) {
            if (obj == null) return 0;
            return (obj.length === +obj.length) ? obj.length : this.keys(obj).length;
        },
        // Get the first element of an array. Passing **n** will return the first N
        // values in the array. The **guard** check
        // allows it to work with `_.map`.
        first: function(array, n, guard) {
            if (array == null) return void 0;
            return (n != null) && !guard ? slice.call(array, 0, n) : array[0];
        },
    // Get the last element of an array. Passing **n** will return the last N
    // values in the array. The **guard** check allows it to work with `_.map`.
    last:function(array, n, guard) {
        if (array == null) return void 0;
        if ((n != null) && !guard) {
            return slice.call(array, Math.max(array.length - n, 0));
        } else {
            return array[array.length - 1];
        }
    },

    // Returns everything but the first entry of the array. Aliased as `tail` and `drop`.
    // Especially useful on the arguments object. Passing an **n** will return
    // the rest N values in the array. The **guard**
    // check allows it to work with `_.map`.
    rest: function(array, n, guard) {
        return slice.call(array, (n == null) || guard ? 1 : n);
    },
    // Return a version of the array that does not contain the specified value(s).
    without:function(array) {
        return this.difference(array, slice.call(arguments, 1));
    },
    // Produce a duplicate-free version of the array. If the array has already
    // been sorted, you have the option of using a faster algorithm.
    // Aliased as `unique`.
    uniq:function(array, isSorted, iterator, context) {
        if (EIAP.util.Obj.isFunction(isSorted)) {
            context = iterator;
            iterator = isSorted;
            isSorted = false;
        }
        var initial = iterator ? this.map(array, iterator, context) : array;
        var results = [];
        var seen = [];
        this.each(initial, function(value, index) {
            if (isSorted ? (!index || seen[seen.length - 1] !== value) : !EIAP.util.Array.contains(seen, value)) {
                seen.push(value);
                results.push(array[index]);
            }
        });
        return results;
    },
    // Produce an array that contains the union: each distinct element from all of
    // the passed-in arrays.
    union:function() {
        return this.uniq(concat.apply(arrayProto, arguments));
    },
    // Produce an array that contains every item shared between all the
    // passed-in arrays.
    intersection:function(array) {
        var rest = slice.call(arguments, 1);
        return this.filter(this.uniq(array), function(item) {
            return EIAP.util.Array.every(rest, function (other) {
                return EIAP.util.Array.indexOf(other, item) >= 0;
            });
        });
    },
    // Take the difference between one array and a number of other arrays.
    // Only the elements present in just the first array will remain.
    difference:function(array) {
        var rest = concat.apply(arrayProto, slice.call(arguments, 1));
        return this.filter(array, function(value) { return !EIAP.util.Array.contains(rest, value); });
    },
    // Zip together multiple lists into a single array -- elements that share
    // an index go together.
    zip:function() {
        var args = slice.call(arguments);
        var length = this.max(this.pluck(args, 'length'));
        var results = new Array(length);
        for (var i = 0; i < length; i++) {
            results[i] = this.pluck(args, "" + i);
        }
        return results;
    },
    // Converts lists into objects. Pass either a single array of `[key, value]`
    // pairs, or two parallel arrays of the same length -- one of keys, and one of
    // the corresponding values.
    object:function(list, values) {
        if (list == null) return {};
        var result = {};
        for (var i = 0, l = list.length; i < l; i++) {
            if (values) {
                result[list[i]] = values[i];
            } else {
                result[list[i][0]] = list[i][1];
            }
        }
        return result;
    },
    // Use a comparator function to figure out the smallest index at which
    // an object should be inserted so as to maintain order. Uses binary search.
    sortedIndex: function(array, obj, iterator, context) {
        iterator = iterator == null ? identity : lookupIterator(iterator);
        var value = iterator.call(context, obj);
        var low = 0, high = array.length;
        while (low < high) {
            var mid = (low + high) >>> 1;
            iterator.call(context, array[mid]) < value ? low = mid + 1 : high = mid;
        }
        return low;
    },
    // If the browser doesn't supply us with indexOf (I'm looking at you, **MSIE**),
    // we need this function. Return the position of the first occurrence of an
    // item in an array, or -1 if the item is not included in the array.
    // Delegates to **ECMAScript 5**'s native `indexOf` if available.
    // If the array is large and already in sort order, pass `true`
    // for **isSorted** to use binary search.
    indexOf:function(array, item, isSorted) {
        if (array == null) return -1;
        var i = 0, l = array.length;
        if (isSorted) {
            if (typeof isSorted == 'number') {
                i = (isSorted < 0 ? Math.max(0, l + isSorted) : isSorted);
            } else {
                i = this.sortedIndex(array, item);
                return array[i] === item ? i : -1;
            }
        }
        if (nativeIndexOf && array.indexOf === nativeIndexOf) return array.indexOf(item, isSorted);
        for (; i < l; i++) if (array[i] === item) return i;
        return -1;
    },
    // Delegates to **ECMAScript 5**'s native `lastIndexOf` if available.
    lastIndexOf:function(array, item, from) {
        if (array == null) return -1;
        var hasIndex = from != null;
        if (nativeLastIndexOf && array.lastIndexOf === nativeLastIndexOf) {
            return hasIndex ? array.lastIndexOf(item, from) : array.lastIndexOf(item);
        }
        var i = (hasIndex ? from : array.length);
        while (i--) if (array[i] === item) return i;
        return -1;
    }
};
})();
﻿(function () {
    var toString = Object.prototype.toString;
    var has = function (obj, key) {
        return Object.prototype.hasOwnProperty.call(obj, key);
    };
    // The cornerstone, an `each` implementation, aka `forEach`.
    // Handles objects with the built-in `forEach`, arrays, and raw objects.
    // Delegates to **ECMAScript 5**'s native `forEach` if available.
    var each = function (obj, iterator, context) {
        if (obj == null) return;
        if (Array.prototype.forEach && obj.forEach === Array.prototype.forEach) {
            obj.forEach(iterator, context);
        } else if (obj.length === +obj.length) {
            for (var i = 0, l = obj.length; i < l; i++) {
                if (iterator.call(context, obj[i], i, obj) === {}) return;
            }
        } else {
            for (var key in obj) {
                if (EIAP.util.Obj.has(obj, key)) {
                    if (iterator.call(context, obj[key], key, obj) === {}) return;
                }
            }
        }
    };
    // Internal recursive comparison function for `isEqual`.
    var eq = function (a, b, aStack, bStack) {
        // Identical objects are equal. `0 === -0`, but they aren't identical.
        // See the Harmony `egal` proposal: http://wiki.ecmascript.org/doku.php?id=harmony:egal.
        if (a === b) return a !== 0 || 1 / a == 1 / b;
        // A strict comparison is necessary because `null == undefined`.
        if (a == null || b == null) return a === b;
        // Compare `[[Class]]` names.
        var className = toString.call(a);
        if (className != toString.call(b)) return false;
        switch (className) {
            // Strings, numbers, dates, and booleans are compared by value.    
            case '[object String]':
                // Primitives and their corresponding object wrappers are equivalent; thus, `"5"` is
                // equivalent to `new String("5")`.
                return a == String(b);
            case '[object Number]':
                // `NaN`s are equivalent, but non-reflexive. An `egal` comparison is performed for
                // other numeric values.
                return a != +a ? b != +b : (a == 0 ? 1 / a == 1 / b : a == +b);
            case '[object Date]':
            case '[object Boolean]':
                // Coerce dates and booleans to numeric primitive values. Dates are compared by their
                // millisecond representations. Note that invalid dates with millisecond representations
                // of `NaN` are not equivalent.
                return +a == +b;
                // RegExps are compared by their source patterns and flags.
            case '[object RegExp]':
                return a.source == b.source &&
                a.global == b.global &&
                a.multiline == b.multiline &&
                a.ignoreCase == b.ignoreCase;
        }
        if (typeof a != 'object' || typeof b != 'object') return false;
        // Assume equality for cyclic structures. The algorithm for detecting cyclic
        // structures is adapted from ES 5.1 section 15.12.3, abstract operation `JO`.
        var length = aStack.length;
        while (length--) {
            // Linear search. Performance is inversely proportional to the number of
            // unique nested structures.
            if (aStack[length] == a) return bStack[length] == b;
        }
        // Add the first object to the stack of traversed objects.
        aStack.push(a);
        bStack.push(b);
        var size = 0, result = true;
        // Recursively compare objects and arrays.
        if (className == '[object Array]') {
            // Compare array lengths to determine if a deep comparison is necessary.
            size = a.length;
            result = size == b.length;
            if (result) {
                // Deep compare the contents, ignoring non-numeric properties.
                while (size--) {
                    if (!(result = eq(a[size], b[size], aStack, bStack))) break;
                }
            }
        } else {
            // Objects with different constructors are not equivalent, but `Object`s
            // from different frames are.
            var aCtor = a.constructor, bCtor = b.constructor;
            if (aCtor !== bCtor && !(EIAP.util.Obj.isFunction(aCtor) && (aCtor instanceof aCtor) &&
                EIAP.util.Obj.isFunction(bCtor) && (bCtor instanceof bCtor))) {
                return false;
            }
            // Deep compare objects.
            for (var key in a) {
                if (EIAP.util.Obj.has(a, key)) {
                    // Count the expected number of properties.
                    size++;
                    // Deep compare each member.
                    if (!(result = EIAP.util.Obj.has(b, key) && eq(a[key], b[key], aStack, bStack))) break;
                }
            }
            // Ensure that both objects contain the same number of properties.
            if (result) {
                for (key in b) {
                    if (EIAP.util.Obj.has(b, key) && !(size--)) break;
                }
                result = !size;
            }
        }
        // Remove the first object from the stack of traversed objects.
        aStack.pop();
        bStack.pop();
        return result;
    };
    EIAP.util.Obj = {
        // Retrieve the names of an object's properties.
        // Delegates to **ECMAScript 5**'s native `Object.keys`
        keys: Object.keys || function (obj) {
            if (obj !== Object(obj)) throw new TypeError('Invalid object');
            var results = [];
            for (var innerKeys in obj)
                if (this.has(obj, key))
                    innerKeys[innerKeys.length] = key;
            return results;
        },
        // Retrieve the values of an object's properties.
        values: function (obj) {
            var values = [];
            for (var key in obj) if (this.has(obj, key)) values.push(obj[key]);
            return values;
        },
        // Convert an object into a list of `[key, value]` pairs.
        pairs: function (obj) {
            var pairs = [];
            for (var key in obj) if (this.has(obj, key)) pairs.push([key, obj[key]]);
            return pairs;
        },
        // Invert the keys and values of an object. The values must be serializable.
        invert: function (obj) {
            var result = {};
            for (var key in obj) if (this.has(obj, key)) result[obj[key]] = key;
            return result;
        },

        // Return a sorted list of the function names available on the object.
        // Aliased as `methods`
        functions: function (obj) {
            var names = [];
            for (var key in obj) {
                if (this.isFunction(obj[key])) names.push(key);
            }
            return names.sort();
        },
        // Extend a given object with all the properties in passed-in object(s).
        extend: function (obj) {
            each(Array.prototype.slice.call(arguments, 1), function (source) {
                if (source) {
                    for (var prop in source) {
                        obj[prop] = source[prop];
                    }
                }
            });
            return obj;
        },
        // Return a copy of the object only containing the whitelisted properties.
        pick: function (obj) {
            var copy = {};
            var innerKeys = Array.prototype.concat.apply(Array.prototype, Array.prototype.slice.call(arguments, 1));
            each(innerKeys, function (key) {
                if (key in obj) copy[key] = obj[key];
            });
            return copy;
        },
        // Return a copy of the object without the blacklisted properties.
        omit: function (obj) {
            var copy = {};
            var keys = Array.prototype.concat.apply(Array.prototype, Array.prototype.slice.call(arguments, 1));
            for (var key in obj) {
                if (!EIAP.util.Array.contains(keys, key)) copy[key] = obj[key];
            }
            return copy;
        },

        // Fill in a given object with default properties.
        defaults: function (obj) {
            each(Array.prototype.slice.call(arguments, 1), function (source) {
                if (source) {
                    for (var prop in source) {
                        if (obj[prop] == null) obj[prop] = source[prop];
                    }
                }
            });
            return obj;
        },
        // Create a (shallow-cloned) duplicate of an object.
        clone: function (obj) {
            if (!this.isObject(obj)) return obj;
            return this.isArray(obj) ? obj.Array.prototype.slice() : this.extend({}, obj);
        },
        // Invokes interceptor with the obj, and then returns obj.
        // The primary purpose of this method is to "tap into" a method chain, in
        // order to perform operations on intermediate results within the chain.
        tap: function (obj, interceptor) {
            interceptor(obj);
            return obj;
        },
        // Perform a deep comparison to check if two objects are equal.
        isEqual: function (a, b) {
            return eq(a, b, [], []);
        },
        // Is a given array, string, or object empty?
        // An "empty" object has no enumerable own-properties.
        isEmpty: function (obj) {
            if (obj == null) return true;
            if (this.isArray(obj) || this.isString(obj)) return obj.length === 0;
            for (var key in obj) if (this.has(obj, key)) return false;
            return true;
        },
        // Is a given value a DOM element?
        isElement: function (obj) {
            return !!(obj && obj.nodeType === 1);
        },
        // Is a given value an array?
        // Delegates to ECMA5's native Array.isArray
        isArray: Array.isArray || function (obj) {
            return toString.call(obj) == '[object Array]';
        },
        // Is a given variable an object?
        isObject: function (obj) {
            return obj === Object(obj);
        },
        // Is a given object a finite number?
        isFinite: function (obj) {
            return isFinite(obj) && !isNaN(parseFloat(obj));
        },
        // Is the given value `NaN`? (NaN is the only number which does not equal itself).
        isNaN: function (obj) {
            return this.isNumber(obj) && obj != +obj;
        },
        // Is a given value a boolean?
        isBoolean: function (obj) {
            return obj === true || obj === false || toString.call(obj) == '[object Boolean]';
        },
        // Is a given value equal to null?
        isNull: function (obj) {
            return obj === null;
        },
        // Is a given variable undefined?
        isUndefined: function (obj) {
            return obj === void 0;
        },
        // Shortcut function for checking if an object has a given property directly
        // on itself (in other words, not on a prototype).
        has: function (obj, key) {
            return has(obj, key);
        }
    };
    // Add some isType methods: isArguments, isFunction, isString, isNumber, isDate, isRegExp.
    each(['Arguments', 'Function', 'String', 'Number', 'Date', 'RegExp'], function (name) {
        EIAP.util.Obj['is' + name] = function (obj) {
            return toString.call(obj) == '[object ' + name + ']';
        };
    });
    // Define a fallback version of the method in browsers (ahem, IE), where
    // there isn't any inspectable "Arguments" type.
    if (!EIAP.util.Obj.isArguments(arguments)) {
        EIAP.util.Obj.isArguments = function (obj) {
            return !!(obj && EIAP.util.Obj.has(obj, 'callee'));
        };
    }
    // Optimize `isFunction` if appropriate.
    if (typeof (/./) !== 'function') {
        EIAP.util.Obj.isFunction = function (obj) {
            return typeof obj === 'function';
        };
    }
})();
EIAP.applyIf(Object, {
    toFormValue: function (a, traditional) {
        if (!a) {
            return a;
        }
        var r20 = /%20/g;
        ///	<summary>
        ///		创建数组或对象的序列化表示形式(适合于在 URL
        ///		查询字符串或 Ajax 请求中使用)。
        ///	</summary>
        ///	<param name="a" type="Object">
        ///		要序列化的数组或对象。
        ///	</param>
        ///	<param name="traditional" type="Boolean">
        ///		一个指示是否执行传统的“浅表”序列化的布尔值。
        ///	</param>
        ///	<returns type="String" />

        var s = [];

        // Set traditional to true for jQuery <= 1.3.2 behavior.
        if (traditional === undefined) {
            traditional = jQuery.ajaxSettings.traditional;
        }
        // If an array was passed in, assume that it is an array of form elements.
        if (jQuery.isArray(a) || a.jquery) {
            // Serialize the form elements
            jQuery.each(a, function () {
                add(this.name, this.value);
            });

        } else {
            // If traditional, encode the "old" way (the way 1.3.2 or older
            // did it), otherwise encode params recursively.
            for (var prefix in a) {
                buildParams(prefix, a[prefix]);
            }
        }
        // Return the resulting serialization
        return s.join("&").replace(r20, "+");

        function buildParams(prefix, obj) {
            if (jQuery.isArray(obj)) {
                // Serialize array item.
                jQuery.each(obj, function (i, v) {
                    if (traditional) {
                        // Treat each array item as a scalar.
                        add(prefix, v);
                    } else {
                        // If array item is non-scalar (array or object), encode its
                        // numeric index to resolve deserialization ambiguity issues.
                        // Note that rack (as of 1.0.0) can't currently deserialize
                        // nested arrays properly, and attempting to do so may cause
                        // a server error. Possible fixes are to modify rack's
                        // deserialization algorithm or to provide an option or flag
                        // to force array serialization to be shallow.
                        buildParams(prefix + "[" + (typeof v === "object" || jQuery.isArray(v) ? i : "") + "]", v);
                    }
                });

            } else if (!traditional && obj != null && typeof obj === "object") {
                // Serialize object item.
                jQuery.each(obj, function (k, v) {
                    //buildParams(prefix + "[" + k + "]", v);
                    buildParams(prefix + "." + k, v);
                });

            } else {
                // Serialize scalar item.
                add(prefix, obj);
            }
        }

        function add(key, value) {
            // If value is a function, invoke it and return its value
            value = jQuery.isFunction(value) ? value() : value;
            if (value == null) {
                s[s.length] = encodeURIComponent(key) + "=";
            } else {
                s[s.length] = encodeURIComponent(key) + "=" + encodeURIComponent(value);
            }
        }
    }
});﻿(function () {
    var strRepeat = function(str, qty) {
        if (qty < 1) return '';
        var result = '';
        while (qty > 0) {
            if (qty & 1) result += str;
            qty >>= 1, str += str;
        }
        return result;
    };
    var parseNumber = function(source) {
        return source * 1 || 0;
    };
    var slice = [].slice;
    EIAP.util.String = {
        //格式化字符串
        format: function (str) {
            var args = arguments;
            return str.replace(new RegExp("{-?[0-9]+}", "g"), function (item) {
                var intVal = parseInt(item.substring(1, item.length - 1));
                var replace;
                if (intVal >= 0) {
                    replace = args[intVal + 1];
                } else if (intVal === -1) {
                    replace = "{";
                } else if (intVal === -2) {
                    replace = "}";
                } else {
                    replace = "";
                }
                return replace;
            });
        },
        //判断字符串是否为空白
        isBlank: function (str) {
            if (str == null) str = '';
            return (/^\s*$/).test(str);
        },
        //Removes all html tags from string.
        stripTags: function (str) {
            if (str == null) return '';
            return String(str).replace(/<\/?[^>]+>/g, '');
        },
        //Converts first letter of the string to uppercase.
        capitalize: function (str) {
            str = str == null ? '' : String(str);
            return str.charAt(0).toUpperCase() + str.slice(1);
        },
        //Compress some whitespaces to one.
        clean: function (str) {
            return this.trim(str).replace(/\s+/g, ' ');
        },
        //count numbers of substr in str 
        count: function (str, substr) {
            if (str == null || substr == null) return 0;

            str = String(str);
            substr = String(substr);

            var count = 0,
                pos = 0,
                length = substr.length;

            while (true) {
                pos = str.indexOf(substr, pos);
                if (pos === -1) break;
                count++;
                pos += length;
            }

            return count;
        },
        //分拆字符串
        chars: function (str) {
            if (str == null) return [];
            return String(str).split('');
        },
        //
        escapeRegExp: function (str) {
            if (str == null) return '';
            return String(str).replace(/([.*+?^=!:${}()|[\]\/\\])/g, '\\$1');
        },
        //替换字符串中指定字符
        splice: function (str, i, howmany, substr) {
            var arr = this.chars(str);
            arr.splice(~~i, ~~howmany, substr);
            return arr.join('');
        },
        //在字符串的某个位置插入字符
        insert: function (str, i, substr) {
            return this.splice(str, i, 0, substr);
        },
        //available only through _.str object, because Underscore has function with the same name.
        include: function (str, needle) {
            if (needle === '') return true;
            if (str == null) return false;
            return String(str).indexOf(needle) !== -1;
        },
        //Joins strings together with given separator
        join: function () {
            var args = slice.call(arguments),
                separator = args.shift();

            if (separator == null) separator = '';

            return args.join(separator);
        },
        //根据\n分割字符串
        lines: function (str) {
            if (str == null) return [];
            return String(str).split("\n");
        },
        //反向排列字符串
        reverse: function (str) {
            return this.chars(str).reverse().join('');
        },
        //判断该字符串是否以指定字符开始
        startsWith: function (str, starts) {
            if (starts === '') return true;
            if (str == null || starts == null) return false;
            str = String(str);
            starts = String(starts);
            return str.length >= starts.length && str.slice(0, starts.length) === starts;
        },
        //判断该字符串是否以指定字符结束
        endsWith: function (str, ends) {
            if (ends === '') return true;
            if (str == null || ends == null) return false;
            str = String(str);
            ends = String(ends);
            return str.length >= ends.length && str.slice(str.length - ends.length) === ends;
        },
        //得出该字符（串）的下一位(最后一个字符)
        succ: function (str) {
            if (str == null) return '';
            str = String(str);
            return str.slice(0, -1) + String.fromCharCode(str.charCodeAt(str.length - 1) + 1);
        },
        //第一个大写
        titleize: function (str) {
            if (str == null) return '';
            return String(str).replace(/(?:^|\s)\S/g, function (c) { return c.toUpperCase(); });
        },
        //
        defaultToWhiteSpace: function (characters) {
            if (characters == null)
                return '\\s';
            else if (characters.source)
                return characters.source;
            else
                return '[' + this.escapeRegExp(characters) + ']';
        },
        //去除字符串前后的空字符
        trim: function (str, characters) {
            if (str == null) return '';
            if (!characters && String.prototype.trim) return String.prototype.trim.call(str);
            characters = defaultToWhiteSpace(characters);
            return String(str).replace(new RegExp('\^' + characters + '+|' + characters + '+$', 'g'), '');
        },
        //Left trim. Similar to trim, but only for left side.
        ltrim: function (str, characters) {
            if (str == null) return '';
            if (!characters && String.prototype.trimLeft) return String.prototype.trimLeft.call(str);
            characters = defaultToWhiteSpace(characters);
            return String(str).replace(new RegExp('^' + characters + '+'), '');
        },
        //Right trim. Similar to trim, but only for right side.
        rtrim: function (str, characters) {
            if (str == null) return '';
            if (!characters && String.prototype.trimRight) return String.prototype.trimRight.call(str);
            characters = defaultToWhiteSpace(characters);
            return String(str).replace(new RegExp(characters + '+$'), '');
        },
        //清空字符串中从指定位置开始的字符
        truncate: function (str, length, truncateStr) {
            if (str == null) return '';
            str = String(str);
            truncateStr = truncateStr || '...';
            length = ~~length;
            return str.length > length ? str.slice(0, length) + truncateStr : str;
        },
        //pads the str with characters until the total string length is equal to the passed length parameter. By default, pads on the left with the space char (" "). padStr is truncated to a single character if necessary.
        pad: function (str, length, padStr, type) {
            str = str == null ? '' : String(str);
            length = ~~length;

            var padlen = 0;

            if (!padStr)
                padStr = ' ';
            else if (padStr.length > 1)
                padStr = padStr.charAt(0);

            switch (type) {
                case 'right':
                    padlen = length - str.length;
                    return str + strRepeat(padStr, padlen);
                case 'both':
                    padlen = length - str.length;
                    return strRepeat(padStr, Math.ceil(padlen / 2)) + str
                        + strRepeat(padStr, Math.floor(padlen / 2));
                default:
                    // 'left'
                    padlen = length - str.length;
                    return strRepeat(padStr, padlen) + str;
            }
        },
        //在字符串左边增加字符
        lpad: function (str, length, padStr) {
            return this.pad(str, length, padStr);
        },
        //在字符串右边增加字符
        rpad: function (str, length, padStr) {
            return this.pad(str, length, padStr, 'right');
        },
        // 返回数值,并精确到小树点后几位
        lrpad: function (str, length, padStr) {
            return this.pad(str, length, padStr, 'both');
        },
        //Parse string to number. Returns NaN if string can't be parsed to number.
        toNumber: function (str, decimals) {
            if (!str) return 0;
            str = this.trim(str);
            if (!str.match(/^-?\d+(?:\.\d+)?$/)) return NaN;
            return parseNumber(parseNumber(str).toFixed(~~decimals));
        },
        //Formats the numbers.
        numberFormat: function (number, dec, dsep, tsep) {
            if (isNaN(number) || number == null) return '';

            number = number.toFixed(~~dec);
            tsep = typeof tsep == 'string' ? tsep : ',';

            var parts = number.split('.'), fnums = parts[0],
                decimals = parts[1] ? (dsep || '.') + parts[1] : '';

            return fnums.replace(/(\d)(?=(?:\d{3})+$)/g, '$1' + tsep) + decimals;
        },
        //Searches a string from left to right for a pattern and returns a substring consisting of the characters in the string that are to the right of the pattern or all string if no match found.
        strRight: function (str, sep) {
            if (str == null) return '';
            str = String(str);
            sep = sep != null ? String(sep) : sep;
            var pos = !sep ? -1 : str.indexOf(sep);
            return ~pos ? str.slice(pos + sep.length, str.length) : str;
        },
        //Searches a string from right to left for a pattern and returns a substring consisting of the characters in the string that are to the right of the pattern or all string if no match found.
        strRightBack: function (str, sep) {
            if (str == null) return '';
            str = String(str);
            sep = sep != null ? String(sep) : sep;
            var pos = !sep ? -1 : str.lastIndexOf(sep);
            return ~pos ? str.slice(pos + sep.length, str.length) : str;
        },
        //Searches a string from left to right for a pattern and returns a substring consisting of the characters in the string that are to the left of the pattern or all string if no match found.
        strLeft: function (str, sep) {
            if (str == null) return '';
            str = String(str);
            sep = sep != null ? String(sep) : sep;
            var pos = !sep ? -1 : str.indexOf(sep);
            return ~pos ? str.slice(0, pos) : str;
        },

        strLeftBack: function (str, sep) {
            if (str == null) return '';
            str += '';
            sep = sep != null ? '' + sep : sep;
            var pos = str.lastIndexOf(sep);
            return ~pos ? str.slice(0, pos) : str;
        },
        //Join an array into a human readable sentence.
        toSentence: function (array, separator, lastSeparator, serial) {
            separator = separator || ', ';
            lastSeparator = lastSeparator || ' and ';
            var a = array.slice(), lastMember = a.pop();

            if (array.length > 2 && serial) lastSeparator = this.rtrim(separator) + lastSeparator;

            return a.length ? a.join(separator) + lastSeparator + lastMember : lastMember;
        },
        //The same as toSentence, but adjusts delimeters to use Serial comma.
        toSentenceSerial: function () {
            var args = slice.call(arguments);
            args[3] = true;
            return this.toSentence.apply(this, args);
        },
        //Surround a string with another string.
        surround: function (str, wrapper) {
            return [wrapper, str, wrapper].join('');
        },
        //Quotes a string.
        quote: function (str) {
            return this.surround(str, '"');
        }
    };
})();﻿(function (undefined) {
    var moment,
        round = Math.round, i,
        // internal storage for language config files
        languages = {},

        // ASP.NET json date format regex
        aspNetJsonRegex = /^\/?Date\((\-?\d+)/i,

        // format tokens
        formattingTokens = /(\[[^\[]*\])|(\\)?(Mo|MM?M?M?|Do|DDDo|DD?D?D?|ddd?d?|do?|w[o|w]?|W[o|W]?|YYYYY|YYYY|YY|a|A|hh?|HH?|mm?|ss?|SS?S?|X|zz?|ZZ?|.)/g,
        localFormattingTokens = /(\[[^\[]*\])|(\\)?(LT|LL?L?L?|l{1,4})/g,

        // parsing tokens
        parseMultipleFormatChunker = /([0-9a-zA-Z\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]+)/gi,

        // parsing token regexes
        parseTokenOneOrTwoDigits = /\d\d?/, // 0 - 99
        parseTokenOneToThreeDigits = /\d{1,3}/, // 0 - 999
        parseTokenThreeDigits = /\d{3}/, // 000 - 999
        parseTokenFourDigits = /\d{1,4}/, // 0 - 9999
        parseTokenSixDigits = /[+\-]?\d{1,6}/, // -999,999 - 999,999
        parseTokenWord = /[0-9]*[a-z\u00A0-\u05FF\u0700-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]+|[\u0600-\u06FF]+\s*?[\u0600-\u06FF]+/i, // any word (or two) characters or numbers including two word month in arabic.
        parseTokenTimezone = /Z|[\+\-]\d\d:?\d\d/i, // +00:00 -00:00 +0000 -0000 or Z
        parseTokenT = /T/i, // T (ISO seperator)
        parseTokenTimestampMs = /[\+\-]?\d+(\.\d{1,3})?/, // 123456789 123456789.123

        // preliminary iso regex
        // 0000-00-00 + T + 00 or 00:00 or 00:00:00 or 00:00:00.000 + +00:00 or +0000
        isoRegex = /^\s*\d{4}-\d\d-\d\d((T| )(\d\d(:\d\d(:\d\d(\.\d\d?\d?)?)?)?)?([\+\-]\d\d:?\d\d)?)?/,
        isoFormat = 'YYYY-MM-DDTHH:mm:ssZ',

        // iso time formats and regexes
        isoTimes = [
            ['HH:mm:ss.S', /(T| )\d\d:\d\d:\d\d\.\d{1,3}/],
            ['HH:mm:ss', /(T| )\d\d:\d\d:\d\d/],
            ['HH:mm', /(T| )\d\d:\d\d/],
            ['HH', /(T| )\d\d/]
        ],

        // timezone chunker "+10:00" > ["10", "00"] or "-1530" > ["-15", "30"]
        parseTimezoneChunker = /([\+\-]|\d\d)/gi,

        // getter and setter names
        proxyGettersAndSetters = 'Month|Date|Hours|Minutes|Seconds|Milliseconds'.split('|'),
        unitMillisecondFactors = {
            'Milliseconds': 1,
            'Seconds': 1e3,
            'Minutes': 6e4,
            'Hours': 36e5,
            'Days': 864e5,
            'Months': 2592e6,
            'Years': 31536e6
        },

        // format function strings
        formatFunctions = {},

        // tokens to ordinalize and pad
        ordinalizeTokens = 'DDD w W M D d'.split(' '),
        paddedTokens = 'M D H h m s w W'.split(' '),

        formatTokenFunctions = {
            M: function () {
                return this.month() + 1;
            },
            MMM: function (format) {
                return this.lang().monthsShort(this, format);
            },
            MMMM: function (format) {
                return this.lang().months(this, format);
            },
            D: function () {
                return this.date();
            },
            DDD: function () {
                return this.dayOfYear();
            },
            d: function () {
                return this.day();
            },
            dd: function (format) {
                return this.lang().weekdaysMin(this, format);
            },
            ddd: function (format) {
                return this.lang().weekdaysShort(this, format);
            },
            dddd: function (format) {
                return this.lang().weekdays(this, format);
            },
            w: function () {
                return this.week();
            },
            W: function () {
                return this.isoWeek();
            },
            YY: function () {
                return leftZeroFill(this.year() % 100, 2);
            },
            YYYY: function () {
                return leftZeroFill(this.year(), 4);
            },
            YYYYY: function () {
                return leftZeroFill(this.year(), 5);
            },
            a: function () {
                return this.lang().meridiem(this.hours(), this.minutes(), true);
            },
            A: function () {
                return this.lang().meridiem(this.hours(), this.minutes(), false);
            },
            H: function () {
                return this.hours();
            },
            h: function () {
                return this.hours() % 12 || 12;
            },
            m: function () {
                return this.minutes();
            },
            s: function () {
                return this.seconds();
            },
            S: function () {
                return ~~(this.milliseconds() / 100);
            },
            SS: function () {
                return leftZeroFill(~~(this.milliseconds() / 10), 2);
            },
            SSS: function () {
                return leftZeroFill(this.milliseconds(), 3);
            },
            Z: function () {
                var a = -this.zone(),
                    b = "+";
                if (a < 0) {
                    a = -a;
                    b = "-";
                }
                return b + leftZeroFill(~~(a / 60), 2) + ":" + leftZeroFill(~~a % 60, 2);
            },
            ZZ: function () {
                var a = -this.zone(),
                    b = "+";
                if (a < 0) {
                    a = -a;
                    b = "-";
                }
                return b + leftZeroFill(~~(10 * a / 6), 4);
            },
            X: function () {
                return this.unix();
            }
        };

    function padToken(func, count) {
        return function (a) {
            return leftZeroFill(func.call(this, a), count);
        };
    }
    function ordinalizeToken(func) {
        return function (a) {
            return this.lang().ordinal(func.call(this, a));
        };
    }

    while (ordinalizeTokens.length) {
        i = ordinalizeTokens.pop();
        formatTokenFunctions[i + 'o'] = ordinalizeToken(formatTokenFunctions[i]);
    }
    while (paddedTokens.length) {
        i = paddedTokens.pop();
        formatTokenFunctions[i + i] = padToken(formatTokenFunctions[i], 2);
    }
    formatTokenFunctions.DDDD = padToken(formatTokenFunctions.DDD, 3);


    /************************************
        Constructors
    ************************************/

    function Language() {

    }

    // Moment prototype object
    function Moment(config) {
        extend(this, config);
    }

    // Duration Constructor
    function Duration(duration) {
        var data = this._data = {},
            years = duration.years || duration.year || duration.y || 0,
            months = duration.months || duration.month || duration.M || 0,
            weeks = duration.weeks || duration.week || duration.w || 0,
            days = duration.days || duration.day || duration.d || 0,
            hours = duration.hours || duration.hour || duration.h || 0,
            minutes = duration.minutes || duration.minute || duration.m || 0,
            seconds = duration.seconds || duration.second || duration.s || 0,
            milliseconds = duration.milliseconds || duration.millisecond || duration.ms || 0;

        // representation for dateAddRemove
        this._milliseconds = milliseconds +
            seconds * 1e3 + // 1000
            minutes * 6e4 + // 1000 * 60
            hours * 36e5; // 1000 * 60 * 60
        // Because of dateAddRemove treats 24 hours as different from a
        // day when working around DST, we need to store them separately
        this._days = days +
            weeks * 7;
        // It is impossible translate months into days without knowing
        // which months you are are talking about, so we have to store
        // it separately.
        this._months = months +
            years * 12;

        // The following code bubbles up values, see the tests for
        // examples of what that means.
        data.milliseconds = milliseconds % 1000;
        seconds += absRound(milliseconds / 1000);

        data.seconds = seconds % 60;
        minutes += absRound(seconds / 60);

        data.minutes = minutes % 60;
        hours += absRound(minutes / 60);

        data.hours = hours % 24;
        days += absRound(hours / 24);

        days += weeks * 7;
        data.days = days % 30;

        months += absRound(days / 30);

        data.months = months % 12;
        years += absRound(months / 12);

        data.years = years;
    }


    /************************************
        Helpers
    ************************************/


    function extend(a, b) {
        for (var i in b) {
            if (b.hasOwnProperty(i)) {
                a[i] = b[i];
            }
        }
        return a;
    }

    function absRound(number) {
        if (number < 0) {
            return Math.ceil(number);
        } else {
            return Math.floor(number);
        }
    }

    // left zero fill a number
    // see http://jsperf.com/left-zero-filling for performance comparison
    function leftZeroFill(number, targetLength) {
        var output = number + '';
        while (output.length < targetLength) {
            output = '0' + output;
        }
        return output;
    }

    // helper function for _.addTime and _.subtractTime
    function addOrSubtractDurationFromMoment(mom, duration, isAdding) {
        var ms = duration._milliseconds,
            d = duration._days,
            M = duration._months,
            currentDate;

        if (ms) {
            mom._d.setTime(+mom + ms * isAdding);
        }
        if (d) {
            mom.date(mom.date() + d * isAdding);
        }
        if (M) {
            currentDate = mom.date();
            mom.date(1)
                .month(mom.month() + M * isAdding)
                .date(Math.min(currentDate, mom.daysInMonth()));
        }
    }

    // check if is an array
    function isArray(input) {
        return Object.prototype.toString.call(input) === '[object Array]';
    }

    // compare two arrays, return the number of differences
    function compareArrays(array1, array2) {
        var len = Math.min(array1.length, array2.length),
            lengthDiff = Math.abs(array1.length - array2.length),
            diffs = 0,
            i;
        for (i = 0; i < len; i++) {
            if (~~array1[i] !== ~~array2[i]) {
                diffs++;
            }
        }
        return diffs + lengthDiff;
    }


    /************************************
        Languages
    ************************************/


    Language.prototype = {
        set: function (config) {
            var prop, i;
            for (i in config) {
                prop = config[i];
                if (typeof prop === 'function') {
                    this[i] = prop;
                } else {
                    this['_' + i] = prop;
                }
            }
        },

        _months: "January_February_March_April_May_June_July_August_September_October_November_December".split("_"),
        months: function (m) {
            return this._months[m.month()];
        },

        _monthsShort: "Jan_Feb_Mar_Apr_May_Jun_Jul_Aug_Sep_Oct_Nov_Dec".split("_"),
        monthsShort: function (m) {
            return this._monthsShort[m.month()];
        },

        monthsParse: function (monthName) {
            var i, mom, regex, output;

            if (!this._monthsParse) {
                this._monthsParse = [];
            }

            for (i = 0; i < 12; i++) {
                // make the regex if we don't have it already
                if (!this._monthsParse[i]) {
                    mom = moment([2000, i]);
                    regex = '^' + this.months(mom, '') + '|^' + this.monthsShort(mom, '');
                    this._monthsParse[i] = new RegExp(regex.replace('.', ''), 'i');
                }
                // test the regex
                if (this._monthsParse[i].test(monthName)) {
                    return i;
                }
            }
        },

        _weekdays: "Sunday_Monday_Tuesday_Wednesday_Thursday_Friday_Saturday".split("_"),
        weekdays: function (m) {
            return this._weekdays[m.day()];
        },

        _weekdaysShort: "Sun_Mon_Tue_Wed_Thu_Fri_Sat".split("_"),
        weekdaysShort: function (m) {
            return this._weekdaysShort[m.day()];
        },

        _weekdaysMin: "Su_Mo_Tu_We_Th_Fr_Sa".split("_"),
        weekdaysMin: function (m) {
            return this._weekdaysMin[m.day()];
        },

        _longDateFormat: {
            LT: "h:mm A",
            L: "MM/DD/YYYY",
            LL: "MMMM D YYYY",
            LLL: "MMMM D YYYY LT",
            LLLL: "dddd, MMMM D YYYY LT"
        },
        longDateFormat: function (key) {
            var output = this._longDateFormat[key];
            if (!output && this._longDateFormat[key.toUpperCase()]) {
                output = this._longDateFormat[key.toUpperCase()].replace(/MMMM|MM|DD|dddd/g, function (val) {
                    return val.slice(1);
                });
                this._longDateFormat[key] = output;
            }
            return output;
        },

        meridiem: function (hours, minutes, isLower) {
            if (hours > 11) {
                return isLower ? 'pm' : 'PM';
            } else {
                return isLower ? 'am' : 'AM';
            }
        },

        _calendar: {
            sameDay: '[Today at] LT',
            nextDay: '[Tomorrow at] LT',
            nextWeek: 'dddd [at] LT',
            lastDay: '[Yesterday at] LT',
            lastWeek: '[last] dddd [at] LT',
            sameElse: 'L'
        },
        calendar: function (key, mom) {
            var output = this._calendar[key];
            return typeof output === 'function' ? output.apply(mom) : output;
        },

        _relativeTime: {
            future: "in %s",
            past: "%s ago",
            s: "a few seconds",
            m: "a minute",
            mm: "%d minutes",
            h: "an hour",
            hh: "%d hours",
            d: "a day",
            dd: "%d days",
            M: "a month",
            MM: "%d months",
            y: "a year",
            yy: "%d years"
        },
        relativeTime: function (number, withoutSuffix, string, isFuture) {
            var output = this._relativeTime[string];
            return (typeof output === 'function') ?
                output(number, withoutSuffix, string, isFuture) :
                output.replace(/%d/i, number);
        },
        pastFuture: function (diff, output) {
            var format = this._relativeTime[diff > 0 ? 'future' : 'past'];
            return typeof format === 'function' ? format(output) : format.replace(/%s/i, output);
        },

        ordinal: function (number) {
            return this._ordinal.replace("%d", number);
        },
        _ordinal: "%d",

        preparse: function (string) {
            return string;
        },

        postformat: function (string) {
            return string;
        },

        week: function (mom) {
            return weekOfYear(mom, this._week.dow, this._week.doy);
        },
        _week: {
            dow: 0, // Sunday is the first day of the week.
            doy: 6  // The week that contains Jan 1st is the first week of the year.
        }
    };

    // Loads a language definition into the `languages` cache.  The function
    // takes a key and optionally values.  If not in the browser and no values
    // are provided, it will load the language file module.  As a convenience,
    // this function also returns the language values.
    function loadLang(key, values) {
        values.abbr = key;
        if (!languages[key]) {
            languages[key] = new Language();
        }
        languages[key].set(values);
        return languages[key];
    }

    // Determines which language definition to use and returns it.
    //
    // With no parameters, it will return the global language.  If you
    // pass in a language key, such as 'en', it will return the
    // definition for 'en', so long as 'en' has already been loaded using
    // moment.lang.
    function getLangDefinition(key) {
        if (!key) {
            return moment.fn._lang;
        }
        if (!languages[key] && hasModule) {
            require('./lang/' + key);
        }
        return languages[key];
    }


    /************************************
        Formatting
    ************************************/


    function removeFormattingTokens(input) {
        if (input.match(/\[.*\]/)) {
            return input.replace(/^\[|\]$/g, "");
        }
        return input.replace(/\\/g, "");
    }

    function makeFormatFunction(format) {
        var array = format.match(formattingTokens), i, length;

        for (i = 0, length = array.length; i < length; i++) {
            if (formatTokenFunctions[array[i]]) {
                array[i] = formatTokenFunctions[array[i]];
            } else {
                array[i] = removeFormattingTokens(array[i]);
            }
        }

        return function (mom) {
            var output = "";
            for (i = 0; i < length; i++) {
                output += typeof array[i].call === 'function' ? array[i].call(mom, format) : array[i];
            }
            return output;
        };
    }

    // format date using native date object
    function formatMoment(m, format) {
        var i = 5;

        function replaceLongDateFormatTokens(input) {
            return m.lang().longDateFormat(input) || input;
        }

        while (i-- && localFormattingTokens.test(format)) {
            format = format.replace(localFormattingTokens, replaceLongDateFormatTokens);
        }

        if (!formatFunctions[format]) {
            formatFunctions[format] = makeFormatFunction(format);
        }

        return formatFunctions[format](m);
    }


    /************************************
        Parsing
    ************************************/


    // get the regex to find the next token
    function getParseRegexForToken(token) {
        switch (token) {
            case 'DDDD':
                return parseTokenThreeDigits;
            case 'YYYY':
                return parseTokenFourDigits;
            case 'YYYYY':
                return parseTokenSixDigits;
            case 'S':
            case 'SS':
            case 'SSS':
            case 'DDD':
                return parseTokenOneToThreeDigits;
            case 'MMM':
            case 'MMMM':
            case 'dd':
            case 'ddd':
            case 'dddd':
            case 'a':
            case 'A':
                return parseTokenWord;
            case 'X':
                return parseTokenTimestampMs;
            case 'Z':
            case 'ZZ':
                return parseTokenTimezone;
            case 'T':
                return parseTokenT;
            case 'MM':
            case 'DD':
            case 'YY':
            case 'HH':
            case 'hh':
            case 'mm':
            case 'ss':
            case 'M':
            case 'D':
            case 'd':
            case 'H':
            case 'h':
            case 'm':
            case 's':
                return parseTokenOneOrTwoDigits;
            default:
                return new RegExp(token.replace('\\', ''));
        }
    }

    // function to convert string input to date
    function addTimeToArrayFromToken(token, input, config) {
        var a, b,
            datePartArray = config._a;

        switch (token) {
            // MONTH
            case 'M': // fall through to MM
            case 'MM':
                datePartArray[1] = (input == null) ? 0 : ~~input - 1;
                break;
            case 'MMM': // fall through to MMMM
            case 'MMMM':
                a = getLangDefinition(config._l).monthsParse(input);
                // if we didn't find a month name, mark the date as invalid.
                if (a != null) {
                    datePartArray[1] = a;
                } else {
                    config._isValid = false;
                }
                break;
                // DAY OF MONTH
            case 'D': // fall through to DDDD
            case 'DD': // fall through to DDDD
            case 'DDD': // fall through to DDDD
            case 'DDDD':
                if (input != null) {
                    datePartArray[2] = ~~input;
                }
                break;
                // YEAR
            case 'YY':
                datePartArray[0] = ~~input + (~~input > 68 ? 1900 : 2000);
                break;
            case 'YYYY':
            case 'YYYYY':
                datePartArray[0] = ~~input;
                break;
                // AM / PM
            case 'a': // fall through to A
            case 'A':
                config._isPm = ((input + '').toLowerCase() === 'pm');
                break;
                // 24 HOUR
            case 'H': // fall through to hh
            case 'HH': // fall through to hh
            case 'h': // fall through to hh
            case 'hh':
                datePartArray[3] = ~~input;
                break;
                // MINUTE
            case 'm': // fall through to mm
            case 'mm':
                datePartArray[4] = ~~input;
                break;
                // SECOND
            case 's': // fall through to ss
            case 'ss':
                datePartArray[5] = ~~input;
                break;
                // MILLISECOND
            case 'S':
            case 'SS':
            case 'SSS':
                datePartArray[6] = ~~(('0.' + input) * 1000);
                break;
                // UNIX TIMESTAMP WITH MS
            case 'X':
                config._d = new Date(parseFloat(input) * 1000);
                break;
                // TIMEZONE
            case 'Z': // fall through to ZZ
            case 'ZZ':
                config._useUTC = true;
                a = (input + '').match(parseTimezoneChunker);
                if (a && a[1]) {
                    config._tzh = ~~a[1];
                }
                if (a && a[2]) {
                    config._tzm = ~~a[2];
                }
                // reverse offsets
                if (a && a[0] === '+') {
                    config._tzh = -config._tzh;
                    config._tzm = -config._tzm;
                }
                break;
        }

        // if the input is null, the date is not valid
        if (input == null) {
            config._isValid = false;
        }
    }

    // convert an array to a date.
    // the array should mirror the parameters below
    // note: all values past the year are optional and will default to the lowest possible value.
    // [year, month, day , hour, minute, second, millisecond]
    function dateFromArray(config) {
        var i, date, input = [];

        if (config._d) {
            return;
        }

        for (i = 0; i < 7; i++) {
            config._a[i] = input[i] = (config._a[i] == null) ? (i === 2 ? 1 : 0) : config._a[i];
        }

        // add the offsets to the time to be parsed so that we can have a clean array for checking isValid
        input[3] += config._tzh || 0;
        input[4] += config._tzm || 0;

        date = new Date(0);

        if (config._useUTC) {
            date.setUTCFullYear(input[0], input[1], input[2]);
            date.setUTCHours(input[3], input[4], input[5], input[6]);
        } else {
            date.setFullYear(input[0], input[1], input[2]);
            date.setHours(input[3], input[4], input[5], input[6]);
        }

        config._d = date;
    }

    // date from string and format string
    function makeDateFromStringAndFormat(config) {
        // This array is used to make a Date, either with `new Date` or `Date.UTC`
        var tokens = config._f.match(formattingTokens),
            string = config._i,
            i, parsedInput;

        config._a = [];

        for (i = 0; i < tokens.length; i++) {
            parsedInput = (getParseRegexForToken(tokens[i]).exec(string) || [])[0];
            if (parsedInput) {
                string = string.slice(string.indexOf(parsedInput) + parsedInput.length);
            }
            // don't parse if its not a known token
            if (formatTokenFunctions[tokens[i]]) {
                addTimeToArrayFromToken(tokens[i], parsedInput, config);
            }
        }
        // handle am pm
        if (config._isPm && config._a[3] < 12) {
            config._a[3] += 12;
        }
        // if is 12 am, change hours to 0
        if (config._isPm === false && config._a[3] === 12) {
            config._a[3] = 0;
        }
        // return
        dateFromArray(config);
    }

    // date from string and array of format strings
    function makeDateFromStringAndArray(config) {
        var tempConfig,
            tempMoment,
            bestMoment,

            scoreToBeat = 99,
            i,
            currentDate,
            currentScore;

        while (config._f.length) {
            tempConfig = extend({}, config);
            tempConfig._f = config._f.pop();
            makeDateFromStringAndFormat(tempConfig);
            tempMoment = new Moment(tempConfig);

            if (tempMoment.isValid()) {
                bestMoment = tempMoment;
                break;
            }

            currentScore = compareArrays(tempConfig._a, tempMoment.toArray());

            if (currentScore < scoreToBeat) {
                scoreToBeat = currentScore;
                bestMoment = tempMoment;
            }
        }

        extend(config, bestMoment);
    }

    // date from iso format
    function makeDateFromString(config) {
        var i,
            string = config._i;
        if (isoRegex.exec(string)) {
            config._f = 'YYYY-MM-DDT';
            for (i = 0; i < 4; i++) {
                if (isoTimes[i][1].exec(string)) {
                    config._f += isoTimes[i][0];
                    break;
                }
            }
            if (parseTokenTimezone.exec(string)) {
                config._f += " Z";
            }
            makeDateFromStringAndFormat(config);
        } else {
            config._d = new Date(string);
        }
    }

    function makeDateFromInput(config) {
        var input = config._i,
            matched = aspNetJsonRegex.exec(input);

        if (input === undefined) {
            config._d = new Date();
        } else if (matched) {
            config._d = new Date(+matched[1]);
        } else if (typeof input === 'string') {
            makeDateFromString(config);
        } else if (isArray(input)) {
            config._a = input.slice(0);
            dateFromArray(config);
        } else {
            config._d = input instanceof Date ? new Date(+input) : new Date(input);
        }
    }


    /************************************
        Relative Time
    ************************************/


    // helper function for moment.fn.from, moment.fn.fromNow, and moment.duration.fn.humanize
    function substituteTimeAgo(string, number, withoutSuffix, isFuture, lang) {
        return lang.relativeTime(number || 1, !!withoutSuffix, string, isFuture);
    }

    function relativeTime(milliseconds, withoutSuffix, lang) {
        var seconds = round(Math.abs(milliseconds) / 1000),
            minutes = round(seconds / 60),
            hours = round(minutes / 60),
            days = round(hours / 24),
            years = round(days / 365),
            args = seconds < 45 && ['s', seconds] ||
                minutes === 1 && ['m'] ||
                minutes < 45 && ['mm', minutes] ||
                hours === 1 && ['h'] ||
                hours < 22 && ['hh', hours] ||
                days === 1 && ['d'] ||
                days <= 25 && ['dd', days] ||
                days <= 45 && ['M'] ||
                days < 345 && ['MM', round(days / 30)] ||
                years === 1 && ['y'] || ['yy', years];
        args[2] = withoutSuffix;
        args[3] = milliseconds > 0;
        args[4] = lang;
        return substituteTimeAgo.apply({}, args);
    }


    /************************************
        Week of Year
    ************************************/


    // firstDayOfWeek       0 = sun, 6 = sat
    //                      the day of the week that starts the week
    //                      (usually sunday or monday)
    // firstDayOfWeekOfYear 0 = sun, 6 = sat
    //                      the first week is the week that contains the first
    //                      of this day of the week
    //                      (eg. ISO weeks use thursday (4))
    function weekOfYear(mom, firstDayOfWeek, firstDayOfWeekOfYear) {
        var end = firstDayOfWeekOfYear - firstDayOfWeek,
            daysToDayOfWeek = firstDayOfWeekOfYear - mom.day();


        if (daysToDayOfWeek > end) {
            daysToDayOfWeek -= 7;
        }

        if (daysToDayOfWeek < end - 7) {
            daysToDayOfWeek += 7;
        }

        return Math.ceil(moment(mom).add('d', daysToDayOfWeek).dayOfYear() / 7);
    }


    /************************************
        Top Level Functions
    ************************************/

    function makeMoment(config) {
        var input = config._i,
            format = config._f;

        if (input === null || input === '') {
            return null;
        }

        if (typeof input === 'string') {
            config._i = input = getLangDefinition().preparse(input);
        }

        if (moment.isMoment(input)) {
            config = extend({}, input);
            config._d = new Date(+input._d);
        } else if (format) {
            if (isArray(format)) {
                makeDateFromStringAndArray(config);
            } else {
                makeDateFromStringAndFormat(config);
            }
        } else {
            makeDateFromInput(config);
        }

        return new Moment(config);
    }

    moment = function (input, format, lang) {
        return makeMoment({
            _i: input,
            _f: format,
            _l: lang,
            _isUTC: false
        });
    };

    // creating with utc
    moment.utc = function (input, format, lang) {
        return makeMoment({
            _useUTC: true,
            _isUTC: true,
            _l: lang,
            _i: input,
            _f: format
        });
    };

    // creating with unix timestamp (in seconds)
    moment.unix = function (input) {
        return moment(input * 1000);
    };

    // duration
    moment.duration = function (input, key) {
        var isDuration = moment.isDuration(input),
            isNumber = (typeof input === 'number'),
            duration = (isDuration ? input._data : (isNumber ? {} : input)),
            ret;

        if (isNumber) {
            if (key) {
                duration[key] = input;
            } else {
                duration.milliseconds = input;
            }
        }

        ret = new Duration(duration);

        if (isDuration && input.hasOwnProperty('_lang')) {
            ret._lang = input._lang;
        }

        return ret;
    };

    // default format
    moment.defaultFormat = isoFormat;

    // This function will load languages and then set the global language.  If
    // no arguments are passed in, it will simply return the current global
    // language key.
    moment.lang = function (key, values) {
        var i;

        if (!key) {
            return moment.fn._lang._abbr;
        }
        if (values) {
            loadLang(key, values);
        } else if (!languages[key]) {
            getLangDefinition(key);
        }
        moment.duration.fn._lang = moment.fn._lang = getLangDefinition(key);
    };

    // returns language data
    moment.langData = function (key) {
        if (key && key._lang && key._lang._abbr) {
            key = key._lang._abbr;
        }
        return getLangDefinition(key);
    };

    // compare moment object
    moment.isMoment = function (obj) {
        return obj instanceof Moment;
    };

    // for typechecking Duration objects
    moment.isDuration = function (obj) {
        return obj instanceof Duration;
    };


    /************************************
        Moment Prototype
    ************************************/


    moment.fn = Moment.prototype = {

        clone: function () {
            return moment(this);
        },

        valueOf: function () {
            return +this._d;
        },

        unix: function () {
            return Math.floor(+this._d / 1000);
        },

        toString: function () {
            return this.format("ddd MMM DD YYYY HH:mm:ss [GMT]ZZ");
        },

        toDate: function () {
            return this._d;
        },

        toJSON: function () {
            return moment.utc(this).format('YYYY-MM-DD[T]HH:mm:ss.SSS[Z]');
        },

        toArray: function () {
            var m = this;
            return [
                m.year(),
                m.month(),
                m.date(),
                m.hours(),
                m.minutes(),
                m.seconds(),
                m.milliseconds()
            ];
        },

        isValid: function () {
            if (this._isValid == null) {
                if (this._a) {
                    this._isValid = !compareArrays(this._a, (this._isUTC ? moment.utc(this._a) : moment(this._a)).toArray());
                } else {
                    this._isValid = !isNaN(this._d.getTime());
                }
            }
            return !!this._isValid;
        },

        utc: function () {
            this._isUTC = true;
            return this;
        },

        local: function () {
            this._isUTC = false;
            return this;
        },

        format: function (inputString) {
            var output = formatMoment(this, inputString || moment.defaultFormat);
            return this.lang().postformat(output);
        },

        add: function (input, val) {
            var dur;
            // switch args to support add('s', 1) and add(1, 's')
            if (typeof input === 'string') {
                dur = moment.duration(+val, input);
            } else {
                dur = moment.duration(input, val);
            }
            addOrSubtractDurationFromMoment(this, dur, 1);
            return this;
        },

        subtract: function (input, val) {
            var dur;
            // switch args to support subtract('s', 1) and subtract(1, 's')
            if (typeof input === 'string') {
                dur = moment.duration(+val, input);
            } else {
                dur = moment.duration(input, val);
            }
            addOrSubtractDurationFromMoment(this, dur, -1);
            return this;
        },

        diff: function (input, units, asFloat) {
            var that = this._isUTC ? moment(input).utc() : moment(input).local(),
                zoneDiff = (this.zone() - that.zone()) * 6e4,
                diff, output;

            if (units) {
                // standardize on singular form
                units = units.replace(/s$/, '');
            }

            if (units === 'year' || units === 'month') {
                diff = (this.daysInMonth() + that.daysInMonth()) * 432e5; // 24 * 60 * 60 * 1000 / 2
                output = ((this.year() - that.year()) * 12) + (this.month() - that.month());
                output += ((this - moment(this).startOf('month')) - (that - moment(that).startOf('month'))) / diff;
                if (units === 'year') {
                    output = output / 12;
                }
            } else {
                diff = (this - that) - zoneDiff;
                output = units === 'second' ? diff / 1e3 : // 1000
                    units === 'minute' ? diff / 6e4 : // 1000 * 60
                    units === 'hour' ? diff / 36e5 : // 1000 * 60 * 60
                    units === 'day' ? diff / 864e5 : // 1000 * 60 * 60 * 24
                    units === 'week' ? diff / 6048e5 : // 1000 * 60 * 60 * 24 * 7
                    diff;
            }
            return asFloat ? output : absRound(output);
        },

        from: function (time, withoutSuffix) {
            return moment.duration(this.diff(time)).lang(this.lang()._abbr).humanize(!withoutSuffix);
        },

        fromNow: function (withoutSuffix) {
            return this.from(moment(), withoutSuffix);
        },

        calendar: function () {
            var diff = this.diff(moment().startOf('day'), 'days', true),
                format = diff < -6 ? 'sameElse' :
                diff < -1 ? 'lastWeek' :
                diff < 0 ? 'lastDay' :
                diff < 1 ? 'sameDay' :
                diff < 2 ? 'nextDay' :
                diff < 7 ? 'nextWeek' : 'sameElse';
            return this.format(this.lang().calendar(format, this));
        },

        isLeapYear: function () {
            var year = this.year();
            return (year % 4 === 0 && year % 100 !== 0) || year % 400 === 0;
        },

        isDST: function () {
            return (this.zone() < moment([this.year()]).zone() ||
                this.zone() < moment([this.year(), 5]).zone());
        },

        day: function (input) {
            var day = this._isUTC ? this._d.getUTCDay() : this._d.getDay();
            return input == null ? day :
                this.add({ d: input - day });
        },

        startOf: function (units) {
            units = units.replace(/s$/, '');
            // the following switch intentionally omits break keywords
            // to utilize falling through the cases.
            switch (units) {
                case 'year':
                    this.month(0);
                    /* falls through */
                case 'month':
                    this.date(1);
                    /* falls through */
                case 'week':
                case 'day':
                    this.hours(0);
                    /* falls through */
                case 'hour':
                    this.minutes(0);
                    /* falls through */
                case 'minute':
                    this.seconds(0);
                    /* falls through */
                case 'second':
                    this.milliseconds(0);
                    /* falls through */
            }

            // weeks are a special case
            if (units === 'week') {
                this.day(0);
            }

            return this;
        },

        endOf: function (units) {
            return this.startOf(units).add(units.replace(/s?$/, 's'), 1).subtract('ms', 1);
        },

        isAfter: function (input, units) {
            units = typeof units !== 'undefined' ? units : 'millisecond';
            return +this.clone().startOf(units) > +moment(input).startOf(units);
        },

        isBefore: function (input, units) {
            units = typeof units !== 'undefined' ? units : 'millisecond';
            return +this.clone().startOf(units) < +moment(input).startOf(units);
        },

        isSame: function (input, units) {
            units = typeof units !== 'undefined' ? units : 'millisecond';
            return +this.clone().startOf(units) === +moment(input).startOf(units);
        },

        zone: function () {
            return this._isUTC ? 0 : this._d.getTimezoneOffset();
        },

        daysInMonth: function () {
            return moment.utc([this.year(), this.month() + 1, 0]).date();
        },

        dayOfYear: function (input) {
            var dayOfYear = round((moment(this).startOf('day') - moment(this).startOf('year')) / 864e5) + 1;
            return input == null ? dayOfYear : this.add("d", (input - dayOfYear));
        },

        isoWeek: function (input) {
            var week = weekOfYear(this, 1, 4);
            return input == null ? week : this.add("d", (input - week) * 7);
        },

        week: function (input) {
            var week = this.lang().week(this);
            return input == null ? week : this.add("d", (input - week) * 7);
        },

        // If passed a language key, it will set the language for this
        // instance.  Otherwise, it will return the language configuration
        // variables for this instance.
        lang: function (key) {
            if (key === undefined) {
                return this._lang;
            } else {
                this._lang = getLangDefinition(key);
                return this;
            }
        },
        getDay: function (days) {
            var curDate = new Date(), year, month, date;
            if (Math.abs(days) > 0) {
                var millSeconds = Math.abs(curDate) + (days * 24 * 60 * 60 * 1000);
                var rDate = new Date(millSeconds);
                year = rDate.getFullYear();
                month = rDate.getMonth() + 1;
                if (month < 10) month = "0" + month;
                date = rDate.getDate();
                if (date < 10) date = "0" + date;
                return (year + "-" + month + "-" + date);
            }
            year = curDate.getFullYear();
            month = curDate.getMonth() + 1;
            if (month < 10) month = "0" + month;
            date = curDate.getDate();
            if (date < 10) date = "0" + date;
            return (year + "-" + month + "-" + date);
        }
    };

    // helper for adding shortcuts
    function makeGetterAndSetter(name, key) {
        moment.fn[name] = moment.fn[name + 's'] = function (input) {
            var utc = this._isUTC ? 'UTC' : '';
            if (input != null) {
                this._d['set' + utc + key](input);
                return this;
            } else {
                return this._d['get' + utc + key]();
            }
        };
    }

    // loop through and add shortcuts (Month, Date, Hours, Minutes, Seconds, Milliseconds)
    for (i = 0; i < proxyGettersAndSetters.length; i++) {
        makeGetterAndSetter(proxyGettersAndSetters[i].toLowerCase().replace(/s$/, ''), proxyGettersAndSetters[i]);
    }

    // add shortcut for year (uses different syntax than the getter/setter 'year' == 'FullYear')
    makeGetterAndSetter('year', 'FullYear');

    // add plural methods
    moment.fn.days = moment.fn.day;
    moment.fn.weeks = moment.fn.week;
    moment.fn.isoWeeks = moment.fn.isoWeek;

    /************************************
        Duration Prototype
    ************************************/


    moment.duration.fn = Duration.prototype = {
        weeks: function () {
            return absRound(this.days() / 7);
        },

        valueOf: function () {
            return this._milliseconds +
              this._days * 864e5 +
              this._months * 2592e6;
        },

        humanize: function (withSuffix) {
            var difference = +this,
                output = relativeTime(difference, !withSuffix, this.lang());

            if (withSuffix) {
                output = this.lang().pastFuture(difference, output);
            }

            return this.lang().postformat(output);
        },

        lang: moment.fn.lang
    };

    function makeDurationGetter(name) {
        moment.duration.fn[name] = function () {
            return this._data[name];
        };
    }

    function makeDurationAsGetter(name, factor) {
        moment.duration.fn['as' + name] = function () {
            return +this / factor;
        };
    }

    for (i in unitMillisecondFactors) {
        if (unitMillisecondFactors.hasOwnProperty(i)) {
            makeDurationAsGetter(i, unitMillisecondFactors[i]);
            makeDurationGetter(i.toLowerCase());
        }
    }

    makeDurationAsGetter('Weeks', 6048e5);


    /************************************
        Default Lang
    ************************************/


    // Set default language, other languages will inherit from English.
    moment.lang('en', {
        ordinal: function (number) {
            var b = number % 10,
                output = (~~(number % 100 / 10) === 1) ? 'th' :
                (b === 1) ? 'st' :
                (b === 2) ? 'nd' :
                (b === 3) ? 'rd' : 'th';
            return number + output;
        }
    });


    /************************************
        Exposing Moment
    ************************************/

    EIAP.util.Date = moment;
}).call(this);﻿EIAP.util.Cookie = {
    /**
    * @param {String} name The name of the cookie to set. 
    * @param {Mixed} value The value to set for the cookie.
    * @param {Object} expires (Optional) Specify an expiration date the
    * @param {String} path (Optional) Setting a path on the cookie restricts
    * @param {String} domain (Optional) Setting a domain restricts access to
    * @param {Boolean} secure (Optional) Specify true to indicate that the cookie
    */
    set: function (name, value, options) {
        options = EIAP.apply({}, options);
        if (typeof options.expires === 'number') {
            var days = options.expires, t = options.expires = new Date();
            t.setDate(t.getDate() + days);
        }
        document.cookie = name + "=" + escape(value) + (options.expires ? ("; expires=" + options.expires.toUTCString()) : "") + (options.path ? ("; path=" + options.path) : "") + (options.domain ? ("; domain=" + options.domain) : "") + (options.secure ? "; secure" : "");
    },
    get: function (name) {
        var arg = name + "=";
        var alen = arg.length;
        var clen = document.cookie.length;
        var i = 0;
        var j = 0;
        while (i < clen) {
            j = i + alen;
            if (document.cookie.substring(i, j) == arg) {
                return EIAP.util.Cookie.getCookieVal(j);
            }
            i = document.cookie.indexOf(" ", i) + 1;
            if (i === 0) {
                break;
            }
        }
        return null;
    },
    clear: function (name, options) {
        var v = EIAP.util.Cookie.get(name);
        if (v) {
            var date = new Date();
            date.setTime(date.getTime() - 10000);
            var options = EIAP.apply({ expires: -1, path: '/', domain: EIAP.util.Cookie.geDefaultDomain() },options);
            EIAP.util.Cookie.set(name, v, options);
        }
    },
    getCookieVal: function (offset) {
        var endstr = document.cookie.indexOf(";", offset);
        if (endstr == -1) {
            endstr = document.cookie.length;
        }
        return unescape(document.cookie.substring(offset, endstr));
    },
    geDefaultDomain: function () {
        var pathroot = EIAP.util.Url.attr("host");
        return pathroot.substring(pathroot.indexOf("."), pathroot.length);
    },
    setCookie: function (entityId, data, options) {
        var doptions = { expires: 1, path: '/', domain: EIAP.util.Cookie.geDefaultDomain() };
        if (options) {
            doptions = EIAP.apply(doptions, options);
        }
        EIAP.util.Cookie.set(entityId, data, doptions);
    },
    deleteCookie: function (entityId, options) {
        EIAP.util.Cookie.clear(entityId);
    }
};
EIAP.setCookie = EIAP.util.Cookie.setCookie;
EIAP.deleteCookie = EIAP.util.Cookie.deleteCookie;
﻿/**
* jQuery Guid v1.0.0-1
* Requires jQuery 1.2.6+ (Not tested with earlier versions).
*/
$.extend(EIAP.util, {
    Guid: {
        set: function() {
            var value;
            if (this.isValid(arguments[0])) {
                value = arguments[0];
            } else {
                value = this.empty();
            }
            $(this).data("value", value);
            return value;
        },
        empty: function () {
            return "00000000-0000-0000-0000-000000000000";
        },
        isEmpty: function (gid) {
            return gid == EIAP.util.Guid.empty() || typeof (gid) == 'undefined' || gid == null || gid == '';
        },
        isValid: function (value) {
            var rGx = new RegExp("\\b(?:[A-F0-9]{8})(?:-[A-F0-9]{4}){3}-(?:[A-F0-9]{12})\\b");
            return rGx.exec(value) != null;
        },
        newGuid: function () {
            var value;
            if (arguments.length == 1 && this.IsValid(arguments[0])) {
                $(this).data("value", arguments[0]);
                value = arguments[0];
                return value;
            }
            var res = [], hv;
            var rgx = new RegExp("[2345]");
            for (var i = 0; i < 8; i++) {
                hv = (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1);
                if (rgx.exec(i.toString()) != null) {
                    if (i == 3) { hv = "6" + hv.substr(1, 3); }
                    res.push("-");
                }
                res.push(hv.toUpperCase());
            }
            value = res.join('');
            $(this).data("value", value);
            return value;
        },
        value: function () {
            if ($(this).data("value")) {
                return $(this).data("value");
            }
            var val = this.newGuid();
            $(this).data("value", val);
            return val;
        }
    }
});﻿(function () {
    var f = function (n) {
        // Format integers to have at least two digits.
        return n < 10 ? '0' + n : n;
    };
    if (typeof Date.prototype.toJSON !== 'function') {
        Date.prototype.toJSON = function () {
            return isFinite(this.valueOf()) ?
                this.getUTCFullYear() + '-' +
                    f(this.getUTCMonth() + 1) + '-' +
                    f(this.getUTCDate()) + 'T' +
                    f(this.getUTCHours()) + ':' +
                    f(this.getUTCMinutes()) + ':' +
                    f(this.getUTCSeconds()) + 'Z' : null;
        };
        String.prototype.toJSON =
            Number.prototype.toJSON =
                Boolean.prototype.toJSON = function () {
                    return this.valueOf();
                };
    }
    var cx = /[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,
        escapable = /[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,
        gap,
        indent,
        meta = {    // table of character substitutions
            '\b': '\\b',
            '\t': '\\t',
            '\n': '\\n',
            '\f': '\\f',
            '\r': '\\r',
            '"': '\\"',
            '\\': '\\\\'
        },
        rep;
    function quote(string) {

        // If the string contains no control characters, no quote characters, and no
        // backslash characters, then we can safely slap some quotes around it.
        // Otherwise we must also replace the offending characters with safe escape
        // sequences.

        escapable.lastIndex = 0;
        return escapable.test(string) ? '"' + string.replace(escapable, function (a) {
            var c = meta[a];
            return typeof c === 'string' ? c :
                '\\u' + ('0000' + a.charCodeAt(0).toString(16)).slice(-4);
        }) + '"' : '"' + string + '"';
    };
    function str(key, holder) {

        // Produce a string from holder[key].

        var i,          // The loop counter.
            k,          // The member key.
            v,          // The member value.
            length,
            mind = gap,
            partial,
            value = holder[key];

        // If the value has a toJSON method, call it to obtain a replacement value.

        if (value && typeof value === 'object' &&
                typeof value.toJSON === 'function') {
            value = value.toJSON(key);
        }

        // If we were called with a replacer function, then call the replacer to
        // obtain a replacement value.

        if (typeof rep === 'function') {
            value = rep.call(holder, key, value);
        }

        // What happens next depends on the value's type.

        switch (typeof value) {
            case 'string':
                return quote(value);

            case 'number':

                // JSON numbers must be finite. Encode non-finite numbers as null.

                return isFinite(value) ? String(value) : 'null';

            case 'boolean':
            case 'null':

                // If the value is a boolean or null, convert it to a string. Note:
                // typeof null does not produce 'null'. The case is included here in
                // the remote chance that this gets fixed someday.

                return String(value);

                // If the type is 'object', we might be dealing with an object or an array or
                // null.

            case 'object':

                // Due to a specification blunder in ECMAScript, typeof null is 'object',
                // so watch out for that case.

                if (!value) {
                    return 'null';
                }

                // Make an array to hold the partial results of stringifying this object value.

                gap += indent;
                partial = [];

                // Is the value an array?

                if (Object.prototype.toString.apply(value) === '[object Array]') {

                    // The value is an array. Stringify every element. Use null as a placeholder
                    // for non-JSON values.

                    length = value.length;
                    for (i = 0; i < length; i += 1) {
                        partial[i] = str(i, value) || 'null';
                    }

                    // Join all of the elements together, separated with commas, and wrap them in
                    // brackets.

                    v = partial.length === 0 ? '[]' : gap ?
                    '[\n' + gap + partial.join(',\n' + gap) + '\n' + mind + ']' :
                    '[' + partial.join(',') + ']';
                    gap = mind;
                    return v;
                }

                // If the replacer is an array, use it to select the members to be stringified.

                if (rep && typeof rep === 'object') {
                    length = rep.length;
                    for (i = 0; i < length; i += 1) {
                        if (typeof rep[i] === 'string') {
                            k = rep[i];
                            v = str(k, value);
                            if (v) {
                                partial.push(quote(k) + (gap ? ': ' : ':') + v);
                            }
                        }
                    }
                } else {

                    // Otherwise, iterate through all of the keys in the object.

                    for (k in value) {
                        if (Object.prototype.hasOwnProperty.call(value, k)) {
                            v = str(k, value);
                            if (v) {
                                partial.push(quote(k) + (gap ? ': ' : ':') + v);
                            }
                        }
                    }
                }

                // Join all of the member texts together, separated with commas,
                // and wrap them in braces.

                v = partial.length === 0 ? '{}' : gap ?
                '{\n' + gap + partial.join(',\n' + gap) + '\n' + mind + '}' :
                '{' + partial.join(',') + '}';
                gap = mind;
                return v;
        }
    };
    $.extend(EIAP.util, {
        Json: {
            stringify: function (value, replacer, space) {
                // The stringify method takes a value and an optional replacer, and an optional
                // space parameter, and returns a JSON text. The replacer can be a function
                // that can replace values, or an array of strings that will select the keys.
                // A default replacer method can be provided. Use of the space parameter can
                // produce text that is more easily readable.
                var i;
                gap = '';
                indent = '';
                // If the space parameter is a number, make an indent string containing that
                // many spaces.
                if (typeof space === 'number') {
                    for (i = 0; i < space; i += 1) {
                        indent += ' ';
                    }
                    // If the space parameter is a string, it will be used as the indent string.
                } else if (typeof space === 'string') {
                    indent = space;
                }
                // If there is a replacer, it must be a function or an array.
                // Otherwise, throw an error.
                rep = replacer;
                if (replacer && typeof replacer !== 'function' &&
                    (typeof replacer !== 'object' ||
                        typeof replacer.length !== 'number')) {
                    throw new Error('JSON.stringify');
                }
                // Make a fake root object containing our value under the key of ''.
                // Return the result of stringifying the value.
                return str('', { '': value });
            },
            parse: function (text, reviver) {
                // The parse method takes a text and an optional reviver function, and returns
                // a JavaScript value if the text is a valid JSON text.
                var j;
                function walk(holder, key) {
                    // The walk method is used to recursively walk the resulting structure so
                    // that modifications can be made.

                    var k, v, value = holder[key];
                    if (value && typeof value === 'object') {
                        for (k in value) {
                            if (Object.prototype.hasOwnProperty.call(value, k)) {
                                v = walk(value, k);
                                if (v !== undefined) {
                                    value[k] = v;
                                } else {
                                    delete value[k];
                                }
                            }
                        }
                    }
                    return reviver.call(holder, key, value);
                }
                // Parsing happens in four stages. In the first stage, we replace certain
                // Unicode characters with escape sequences. JavaScript handles many characters
                // incorrectly, either silently deleting them, or treating them as line endings.
                text = String(text);
                cx.lastIndex = 0;
                if (cx.test(text)) {
                    text = text.replace(cx, function (a) {
                        return '\\u' +
                        ('0000' + a.charCodeAt(0).toString(16)).slice(-4);
                    });
                }
                // In the second stage, we run the text against regular expressions that look
                // for non-JSON patterns. We are especially concerned with '()' and 'new'
                // because they can cause invocation, and '=' because it can cause mutation.
                // But just to be safe, we want to reject all unexpected forms.
                // We split the second stage into 4 regexp operations in order to work around
                // crippling inefficiencies in IE's and Safari's regexp engines. First we
                // replace the JSON backslash pairs with '@' (a non-JSON character). Second, we
                // replace all simple value tokens with ']' characters. Third, we delete all
                // open brackets that follow a colon or comma or that begin the text. Finally,
                // we look to see that the remaining characters are only whitespace or ']' or
                // ',' or ':' or '{' or '}'. If that is so, then the text is safe for eval.
                if (/^[\],:{}\s]*$/
                    .test(text.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g, '@')
                        .replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, ']')
                        .replace(/(?:^|:|,)(?:\s*\[)+/g, ''))) {
                    // In the third stage we use the eval function to compile the text into a
                    // JavaScript structure. The '{' operator is subject to a syntactic ambiguity
                    // in JavaScript: it can begin a block or an object literal. We wrap the text
                    // in parens to eliminate the ambiguity.
                    j = eval('(' + text + ')');
                    // In the optional fourth stage, we recursively walk the new structure, passing
                    // each name/value pair to a reviver function for possible transformation.
                    return typeof reviver === 'function' ?
                    walk({ '': j }, '') : j;
                }
                // If the text is not JSON parseable, then a SyntaxError is thrown.
                throw new SyntaxError('JSON.parse');
            }
        }
    });
})();﻿// JQuery URL Parser
// Written by Mark Perkins, mark@allmarkedup.com
// License: http://unlicense.org/ (i.e. do what you want with it!)

EIAP.util.Url = function () {
    var segments = {};

    var parsed = {};

    /**
    * Options object. Only the URI and strictMode values can be changed via the setters below.
    */
    var options = {

        url: window.location, // default URI is the page in which the script is running

        strictMode: false, // 'loose' parsing by default

        key: ["source", "protocol", "authority", "userInfo", "user", "password", "host", "port", "relative", "path", "directory", "file", "query", "anchor"], // keys available to query 

        q: {
            name: "queryKey",
            parser: /(?:^|&)([^&=]*)=?([^&]*)/g
        },

        parser: {
            strict: /^(?:([^:\/?#]+):)?(?:\/\/((?:(([^:@]*):?([^:@]*))?@)?([^:\/?#]*)(?::(\d*))?))?((((?:[^?#\/]*\/)*)([^?#]*))(?:\?([^#]*))?(?:#(.*))?)/,  //less intuitive, more accurate to the specs
            loose: /^(?:(?![^:@]+:[^:@\/]*@)([^:\/?#.]+):)?(?:\/\/)?((?:(([^:@]*):?([^:@]*))?@)?([^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/ // more intuitive, fails on relative paths and deviates from specs
        }

    };

    /**
    * Deals with the parsing of the URI according to the regex above.
    * Written by Steven Levithan - see credits at top.
    */
    var parseUri = function () {
        str = decodeURI(options.url);

        var m = options.parser[options.strictMode ? "strict" : "loose"].exec(str);
        var uri = {};
        var i = 14;

        while (i--) {
            uri[options.key[i]] = m[i] || "";
        }

        uri[options.q.name] = {};
        uri[options.key[12]].replace(options.q.parser, function ($0, $1, $2) {
            if ($1) {
                uri[options.q.name][$1] = $2;
            }
        });

        return uri;
    };

    /**
    * Returns the value of the passed in key from the parsed URI.
    * 
    * @param string key The key whose value is required
    */
    var key = function (key) {
        if (jQuery.isEmptyObject(parsed)) {
            setUp(); // if the URI has not been parsed yet then do this first...	
        }
        if (key == "base") {
            if (parsed.port !== null && parsed.port !== "") {
                return parsed.protocol + "://" + parsed.host + ":" + parsed.port + "/";
            }
            else {
                return parsed.protocol + "://" + parsed.host + "/";
            }
        }

        return (parsed[key] === "") ? null : parsed[key];
    };

    /**
    * Returns the value of the required query string parameter.
    * 
    * @param string item The parameter whose value is required
    */
    var param = function (item) {
        if (jQuery.isEmptyObject(parsed)) {
            setUp(); // if the URI has not been parsed yet then do this first...	
        }
        return (parsed.queryKey[item] === null) ? null : parsed.queryKey[item];
    };

    /**
    * 'Constructor' (not really!) function.
    *  Called whenever the URI changes to kick off re-parsing of the URI and splitting it up into segments. 
    */
    var setUp = function () {
        parsed = parseUri();

        getSegments();
    };

    /**
    * Splits up the body of the URI into segments (i.e. sections delimited by '/')
    */
    var getSegments = function () {
        var p = parsed.path;
        segments = []; // clear out segments array
        segments = parsed.path.length == 1 ? {} : (p.charAt(p.length - 1) == "/" ? p.substring(1, p.length - 1) : path = p.substring(1)).split("/");
    };

    return {

        /**
        * Sets the parsing mode - either strict or loose. Set to loose by default.
        *
        * @param string mode The mode to set the parser to. Anything apart from a value of 'strict' will set it to loose!
        */
        setMode: function (mode) {
            options.strictMode = mode == "strict" ? true : false;
            return this;
        },

        /**
        * Sets URI to parse if you don't want to to parse the current page's URI.
        * Calling the function with no value for newUri resets it to the current page's URI.
        *
        * @param string newUri The URI to parse.
        */
        setUrl: function (newUri) {
            options.url = newUri === undefined ? window.location : newUri;
            setUp();
            return this;
        },

        /**
        * Returns the value of the specified URI segment. Segments are numbered from 1 to the number of segments.
        * For example the URI http://test.com/about/company/ segment(1) would return 'about'.
        *
        * If no integer is passed into the function it returns the number of segments in the URI.
        *
        * @param int pos The position of the segment to return. Can be empty.
        */
        segment: function (pos) {
            if (jQuery.isEmptyObject(parsed)) {
                setUp(); // if the URI has not been parsed yet then do this first...	
            }
            if (pos === undefined) {
                return segments.length;
            }
            return (segments[pos] === "" || segments[pos] === undefined) ? null : segments[pos];
        },

        attr: key, // provides public access to private 'key' function - see above

        param: param // provides public access to private 'param' function - see above

    };

} ();﻿EIAP.util.Math = {
    //乘法函数，用来得到精确的乘法结果
    //说明：javascript的乘法结果会有误差，在两个浮点数相乘的时候会比较明显。这个函数返回较为精确的乘法结果。 
    mul: function(arg1, arg2) {
        var m = 0, s1 = arg1.toString(), s2 = arg2.toString();
        try {
            m += s1.split(".")[1].length;
        } catch(e) {
        }
        try {
            m += s2.split(".")[1].length;
        } catch(e) {
        }
        return Number(s1.replace(".", "")) * Number(s2.replace(".", "")) / Math.pow(10, m);
    },
    //除法函数，用来得到精确的除法结果 
    //说明：javascript的除法结果会有误差，在两个浮点数相除的时候会比较明显。这个函数返回较为精确的除法结果。 
    div: function div(arg1, arg2) {
        return this.mul(arg1, 1 / arg2);
    },
    //加法函数，用来得到精确的加法结果 
    //说明：javascript的加法结果会有误差，在两个浮点数相加的时候会比较明显。这个函数返回较为精确的加法结果。 
    add: function(arg1, arg2) {
        var r1, r2, m;
        try {
            r1 = arg1.toString().split(".")[1].length;
        } catch(e) {
            r1 = 0;
        }
        try {
            r2 = arg2.toString().split(".")[1].length;
        } catch(e) {
            r2 = 0;
        }
        m = Math.pow(10, Math.max(r1, r2));
        return (this.mul(arg1, m) + this.mul(arg2, m)) / m;
    },
    //减法函数，用来得到精确的减法结果
    //说明：javascript的减法结果会有误差，在两个浮点数减法的时候会比较明显。这个函数返回较为精确的减法结果。 
    sub: function(arg1, arg2) {
        return this.add(arg1, -arg2);
    },
    // Return a random integer between min and max (inclusive).
    random: function(min, max) {
        if (max == null) {
            max = min;
            min = 0;
        }
        return min + Math.floor(Math.random() * (max - min + 1));
    }
};﻿EIAP.util.DomStyle = {
    cssToObj: function (cssArr) {
        var obj = {};
        if (cssArr) {
            cssArr = cssArr.replace(/(^\s*)|(\s*$)/g,'').split(";");
            for (var i = 0; i < cssArr.length; i++) {
                if (cssArr[i] != "") {
                    var tmpobj = cssArr[i].split(":");
                    if (tmpobj.length == 2) {
                        obj[tmpobj[0]] = tmpobj[1];
                    }
                }
            }
        }
        return obj;
    },
    objToCss: function (sobj) {
        var styleStr = "";
        for (var t in sobj) {
            styleStr = styleStr + t + ":" + sobj[t] + ";";
        }
        return styleStr;
    },
    removeStyle: function (curObj, rCssObj) {
        for (var t in rCssObj) {
            delete curObj[t];
        }
        return curObj;
    }
};﻿EIAP.util.Skin = {
    initSkin: function (key) {
        var skin = this.getSkin(key);
        this.swapSkin(skin);
        this.initImagBlankUrl();
    },
    getSkin: function (key) {
        key = key || "EIAP.skin";
        var skin = EIAP.util.Cookie.get(key);
        if (skin) {
            return skin;
        } else {
            return "default";
        }
    },
    setSkin: function (key, value) {
        key = key || "EIAP.skin";
        value = value || "default";
        EIAP.util.Cookie.set(key, value, { path: "/" });
        this.swapSkin(value);
    },
    swapSkin: function (skin) {
        var skinLink = $('link[href*="eiap-all-min.css"]');
        if (skinLink.length == 0) {
            skinLink = $('link[href*="eiap-all.css"]');
        }
        if (skinLink.length == 1) {
            var linkurl = skinLink.attr('href');
            var linkarr = linkurl.split("/");
            linkarr[linkarr.length - 2] = skin;
            var newlink = "";
            for (var i = 0; i < linkarr.length; i++) {
                newlink += linkarr[i].toString() + "/";
            }
            skinLink.attr("href", newlink.substring(0, newlink.length - 1));
        }
    },
    initImagBlankUrl: function () {
        if (window.location.host.indexOf("rsdn.rcsit.cn") != -1) {
            EIAP.BLANK_IMAGE_URL = "http://rsdn.rcsit.cn/sei-ui/resources/images/s.gif";
        }
        else if (window.location.host.indexOf("localhost:62100") == -1) {
            var scriptPath = $('script[src*="eiap-all"]').attr('src');
            var uiPath = scriptPath.substring(0, scriptPath.lastIndexOf("/"));
            EIAP.BLANK_IMAGE_URL = uiPath + "/resources/images/s.gif";
        }
    }
};
EIAP.util.Skin.initSkin();EIAP.util.Password = function () {
    //var hexcase = 0;  /* hex output format. 0 - lowercase; 1 - uppercase        */
    var b64pad = "="; /* base-64 pad character. "=" for strict RFC compliance   */
    var chrsz = 8;  /* bits per input character. 8 - ASCII; 16 - Unicode      */
    /*
     * Convert a string to an array of little-endian words
     * If chrsz is ASCII, characters >255 have their hi-byte silently ignored.
     */
    var str2binl = function (str) {
        var bin = Array();
        var mask = (1 << chrsz) - 1;
        for (var i = 0; i < str.length * chrsz; i += chrsz)
            bin[i >> 5] |= (str.charCodeAt(i / chrsz) & mask) << (i % 32);
        return bin;
    }

    /* Convert an array of little-endian words to a base-64 string  */
    var binl2b64 = function (binarray) {
        var tab = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
        var str = "";
        for (var i = 0; i < binarray.length * 4; i += 3) {
            var triplet = (((binarray[i >> 2] >> 8 * (i % 4)) & 0xFF) << 16)
                        | (((binarray[i + 1 >> 2] >> 8 * ((i + 1) % 4)) & 0xFF) << 8)
                        | ((binarray[i + 2 >> 2] >> 8 * ((i + 2) % 4)) & 0xFF);
            for (var j = 0; j < 4; j++) {
                if (i * 8 + j * 6 > binarray.length * 32) str += b64pad;
                else str += tab.charAt((triplet >> 6 * (3 - j)) & 0x3F);
            }
        }
        return str;
    }

    /* Calculate the MD5 of an array of little-endian words, and a bit length     */
    var core_md5 = function (x, len) {
        /* append padding */
        x[len >> 5] |= 0x80 << ((len) % 32);
        x[(((len + 64) >>> 9) << 4) + 14] = len;

        var a = 1732584193;
        var b = -271733879;
        var c = -1732584194;
        var d = 271733878;

        for (var i = 0; i < x.length; i += 16) {
            var olda = a;
            var oldb = b;
            var oldc = c;
            var oldd = d;

            a = md5_ff(a, b, c, d, x[i + 0], 7, -680876936);
            d = md5_ff(d, a, b, c, x[i + 1], 12, -389564586);
            c = md5_ff(c, d, a, b, x[i + 2], 17, 606105819);
            b = md5_ff(b, c, d, a, x[i + 3], 22, -1044525330);
            a = md5_ff(a, b, c, d, x[i + 4], 7, -176418897);
            d = md5_ff(d, a, b, c, x[i + 5], 12, 1200080426);
            c = md5_ff(c, d, a, b, x[i + 6], 17, -1473231341);
            b = md5_ff(b, c, d, a, x[i + 7], 22, -45705983);
            a = md5_ff(a, b, c, d, x[i + 8], 7, 1770035416);
            d = md5_ff(d, a, b, c, x[i + 9], 12, -1958414417);
            c = md5_ff(c, d, a, b, x[i + 10], 17, -42063);
            b = md5_ff(b, c, d, a, x[i + 11], 22, -1990404162);
            a = md5_ff(a, b, c, d, x[i + 12], 7, 1804603682);
            d = md5_ff(d, a, b, c, x[i + 13], 12, -40341101);
            c = md5_ff(c, d, a, b, x[i + 14], 17, -1502002290);
            b = md5_ff(b, c, d, a, x[i + 15], 22, 1236535329);

            a = md5_gg(a, b, c, d, x[i + 1], 5, -165796510);
            d = md5_gg(d, a, b, c, x[i + 6], 9, -1069501632);
            c = md5_gg(c, d, a, b, x[i + 11], 14, 643717713);
            b = md5_gg(b, c, d, a, x[i + 0], 20, -373897302);
            a = md5_gg(a, b, c, d, x[i + 5], 5, -701558691);
            d = md5_gg(d, a, b, c, x[i + 10], 9, 38016083);
            c = md5_gg(c, d, a, b, x[i + 15], 14, -660478335);
            b = md5_gg(b, c, d, a, x[i + 4], 20, -405537848);
            a = md5_gg(a, b, c, d, x[i + 9], 5, 568446438);
            d = md5_gg(d, a, b, c, x[i + 14], 9, -1019803690);
            c = md5_gg(c, d, a, b, x[i + 3], 14, -187363961);
            b = md5_gg(b, c, d, a, x[i + 8], 20, 1163531501);
            a = md5_gg(a, b, c, d, x[i + 13], 5, -1444681467);
            d = md5_gg(d, a, b, c, x[i + 2], 9, -51403784);
            c = md5_gg(c, d, a, b, x[i + 7], 14, 1735328473);
            b = md5_gg(b, c, d, a, x[i + 12], 20, -1926607734);

            a = md5_hh(a, b, c, d, x[i + 5], 4, -378558);
            d = md5_hh(d, a, b, c, x[i + 8], 11, -2022574463);
            c = md5_hh(c, d, a, b, x[i + 11], 16, 1839030562);
            b = md5_hh(b, c, d, a, x[i + 14], 23, -35309556);
            a = md5_hh(a, b, c, d, x[i + 1], 4, -1530992060);
            d = md5_hh(d, a, b, c, x[i + 4], 11, 1272893353);
            c = md5_hh(c, d, a, b, x[i + 7], 16, -155497632);
            b = md5_hh(b, c, d, a, x[i + 10], 23, -1094730640);
            a = md5_hh(a, b, c, d, x[i + 13], 4, 681279174);
            d = md5_hh(d, a, b, c, x[i + 0], 11, -358537222);
            c = md5_hh(c, d, a, b, x[i + 3], 16, -722521979);
            b = md5_hh(b, c, d, a, x[i + 6], 23, 76029189);
            a = md5_hh(a, b, c, d, x[i + 9], 4, -640364487);
            d = md5_hh(d, a, b, c, x[i + 12], 11, -421815835);
            c = md5_hh(c, d, a, b, x[i + 15], 16, 530742520);
            b = md5_hh(b, c, d, a, x[i + 2], 23, -995338651);

            a = md5_ii(a, b, c, d, x[i + 0], 6, -198630844);
            d = md5_ii(d, a, b, c, x[i + 7], 10, 1126891415);
            c = md5_ii(c, d, a, b, x[i + 14], 15, -1416354905);
            b = md5_ii(b, c, d, a, x[i + 5], 21, -57434055);
            a = md5_ii(a, b, c, d, x[i + 12], 6, 1700485571);
            d = md5_ii(d, a, b, c, x[i + 3], 10, -1894986606);
            c = md5_ii(c, d, a, b, x[i + 10], 15, -1051523);
            b = md5_ii(b, c, d, a, x[i + 1], 21, -2054922799);
            a = md5_ii(a, b, c, d, x[i + 8], 6, 1873313359);
            d = md5_ii(d, a, b, c, x[i + 15], 10, -30611744);
            c = md5_ii(c, d, a, b, x[i + 6], 15, -1560198380);
            b = md5_ii(b, c, d, a, x[i + 13], 21, 1309151649);
            a = md5_ii(a, b, c, d, x[i + 4], 6, -145523070);
            d = md5_ii(d, a, b, c, x[i + 11], 10, -1120210379);
            c = md5_ii(c, d, a, b, x[i + 2], 15, 718787259);
            b = md5_ii(b, c, d, a, x[i + 9], 21, -343485551);

            a = safe_add(a, olda);
            b = safe_add(b, oldb);
            c = safe_add(c, oldc);
            d = safe_add(d, oldd);
        }
        return Array(a, b, c, d);

    }

    /* These functions implement the four basic operations the algorithm uses.     */
    var md5_cmn = function (q, a, b, x, s, t) {
        return safe_add(bit_rol(safe_add(safe_add(a, q), safe_add(x, t)), s), b);
    }
    var md5_ff = function (a, b, c, d, x, s, t) {
        return md5_cmn((b & c) | ((~b) & d), a, b, x, s, t);
    }
    var md5_gg = function (a, b, c, d, x, s, t) {
        return md5_cmn((b & d) | (c & (~d)), a, b, x, s, t);
    }
    var md5_hh = function (a, b, c, d, x, s, t) {
        return md5_cmn(b ^ c ^ d, a, b, x, s, t);
    }
    var md5_ii = function (a, b, c, d, x, s, t) {
        return md5_cmn(c ^ (b | (~d)), a, b, x, s, t);
    }

    /*
     * Add integers, wrapping at 2^32. This uses 16-bit operations internally
     * to work around bugs in some JS interpreters.
     */
    var safe_add = function (x, y) {
        var lsw = (x & 0xFFFF) + (y & 0xFFFF);
        var msw = (x >> 16) + (y >> 16) + (lsw >> 16);
        return (msw << 16) | (lsw & 0xFFFF);
    }

    /*
     * Bitwise rotate a 32-bit number to the left.
     */
    var bit_rol = function (num, cnt) {
        return (num << cnt) | (num >>> (32 - cnt));
    }
    var checkIsWeakPassword = function (password, type) {
        switch (type) {
            case 1:
                var charReg = new RegExp("[a-zA-Z]");
                var numReg = new RegExp("[0-9]");
                return !(password.length > 7 && charReg.test(password) && numReg.test(password));
            default:
                return fasle;
        }
    }
    var encryptepassword = function (input, type) {
        switch (type) {
            case 1:
                return binl2b64(core_md5(str2binl(input), input.length * chrsz));
            default:
                return input;
        }
    }
    return {
        init: function (logonForm, passwordFiled, type) {
            switch (type) {
                case 1:
                    logonForm.bind("submit", function () {
                        var password = passwordFiled;
                        if (password) {
                            password.removeAttr("name");
                            var $type = $('<input type="hidden" name="EncrypteType" />');
                            $type.val(type);
                            password.after($type);
                            var $encryptepassword = $('<input type="hidden" name="Password"/>');
                            password.after($encryptepassword);
                            $encryptepassword.val(encryptepassword(password.val(), type));
                            if (checkIsWeakPassword(password.val(), type)) {
                                var $isWeakPassword = $('<input type="hidden" name="IsWeakPassword" />');
                                $isWeakPassword.val(true);
                                $encryptepassword.after($isWeakPassword);
                            }
                        }
                    });
                    break;
                default:
                    break;
            }
        },
        CheckIsWeakPassword: function (password, type) {
            return checkIsWeakPassword(password, type);
        },
        EncryptePassword: function (password, type) {
            return encryptepassword(password, type);
        }
    };
}();﻿EIAP.Store = function () {
    return new EIAP.data.Store(arguments[0]);
};

EIAP.data.Store = function () {
    EIAP.apply(this, arguments[0]);
    if (this.url && this.type.toLowerCase() != "get") {
        var tmp = this.url.split("/");
        if (tmp[tmp.length - 1].indexOf(".") > -1) {
            this.type = "GET";
        }
    }

    if (this.autoLoad == true) {
        this.doLoad();
    }
};

EIAP.apply(EIAP.data.Store.prototype, {
    url: null,
    data: null,
    async: true,
    type: 'POST',
    params: null,
    autoLoad: true,
    dataType: "json",
    postType: "form",
    timeout: 0,
    cache: true,
    success: null,
    failure: null,
    loaded: false,
    contentType: "application/x-www-form-urlencoded",
    doLoad: function () {
        var g = arguments[0] ? arguments[0] : this;
        this.transParams(g);
        $.ajax({
            url: g.url,
            type: g.type,
            dataType: g.dataType,
            timeout: g.timeout,
            async: g.async,
            contentType: g.contentType,
            data: g.params ? g.postParam : undefined,
            success: function () {
                if (typeof arguments[0] == "string") {
                    if (g.failure)
                        g.failure.call(this, arguments[0]);
                } else {
                    g.loaded = true;
                    if (g.success)
                        g.success.call(this, arguments[0]);
                }
            },
            error: function () {
                if (g.failure)
                    g.failure.call(this, arguments[0]);
            }
        });
    },
    load: function () {
        var config = arguments[0] || {};
        EIAP.applyIf(config, this);
        config.autoLoad = true;
        this.doLoad(config);
    },
    transParams: function () {
        var cfg = arguments[0];
        cfg.postParam = {};
        EIAP.apply(cfg.postParam, cfg.params);
        if (cfg.postType == "json") {
            EIAP.util.Json.stringify(cfg.postParam);
            cfg.contentType = "application/json;charset=utf-8";
        } else if (cfg.postType == "form") {
            cfg.postParam = Object.toFormValue(cfg.postParam);
        }
    }
});﻿EIAP.form.Field = EIAP.extend(EIAP.UIComponent, {
    inputType: 'text',
    readonly: false,
    name: null,
    field: null,
    submitValue: null,
    isFormField: true,
    title: null,
    value: null,
    showTitle: true,
    labelFirst: true,
    invalidText: null,
    domCss: "ux-field",
    readonlyCss: "ux-field-readonly",
    disabledCss: "ux-field-disable",
    labelCss: "ux-field-label",
    elementCss: "ux-field-element",
    requiredCss: "ux-field-must",
    initComponent: function () {
        EIAP.form.Field.superclass.initComponent.call(this);
        if (!this.labelFirst) {
            this.labelCss = "ux-field-label-right";
        }
    },

    __getType: function () {
        return 'Field';
    },

    __idPrev: function () {
        return 'Field';
    },
    _extMethods: function () {
        return EIAP.form.Field;
    },
    _render: function () {
        var g = this;
        g.dom = g.renderTo ? $(g.element) : $("<div></div>");
        g.dom.addClass(g.domCss);
        g.initLabel();
        g.initField();
        g.addCss();
        g.initAttribute();
        g.addEvents();
        if (g.value != null && g.value != "" && g.value != undefined) {
            if (!(typeof g.value == "object")) {
                g.setValue(g.value);
            } else
                g.loadData(g.value);
        } else {
            g.initSubmitValue();
        }
    },
    show: function () {
        EIAP.form.Field.superclass.show.call(this);
        this.hidden = false;
    },
    hide: function () {
        EIAP.form.Field.superclass.hide.call(this);
        this.hidden = true;
    },
    getLabel: function () {
        var g = this, v = "";
        if (g.title) {
            v = g.title;     //.replace(/[^\u4e00-\u9fa5]/gi, "")   (表单元素title去除英文筛选)
        }
        return v;
    },
    initLabel: function () {
        var g = this;
        if (g.title) {
            var titleText = !g.labelFirst ? g.title : g.title + "：";
            var label = $("<label>" + titleText + "</label>");
            if (g.showTitle) label.attr("title", g.getLabel());
            label.addClass(g.labelCss);
            g.dom.label = label;
            g.dom.append(label);
            g.setLabelWidth(g.labelWidth ? g.labelWidth : 70);
        }
    },
    setTitle: function () {
        var g = this, ags = arguments;
        if (ags.length > 0) {
            g.title = ags[0];
            g.dom.label.html(!g.labelFirst ? ags[0] : ags[0] + "：");
        }
    },
    setLabelWidth: function () {
        var width = parseInt(arguments[0]);
        if (this.dom.label && width) {
            this.dom.label.width(width);
        }
    },
    initField: function () {
        var g = this;
        var input = $("<input type='" + g.inputType + "'>");
        input.addClass(g.fieldCss);
        g.dom.field = input;
        g.dom.fieldwrap = $("<div></div>").addClass(g.elementCss);

        g.dom.fieldwrap.append(g.dom.field);
        if (g.labelFirst) {
            g.dom.append(g.dom.fieldwrap);
        } else {
            g.dom.fieldwrap.insertBefore(g.dom.label);
        }
        g.dom.append('<div class="ux-clear"></div>');
    },

    addCss: function () {
        var g = this;
        if (g.readonly) {
            g.dom.field.attr("readonly", g.readonly);
            g.dom.field.addClass(g.readonlyCss);
        }
        //        if (g.disabled) {
        //            g.dom.attr("disabled", g.disabled);
        //            g.dom.addClass(g.disabledCss);
        //        }
    },

    initAttribute: function () {
        var g = this;
        if (g.readonly) {
            g.dom.field.addClass(g.readonlyCss);
        }
        if (g.disabled) {
            g.dom.field.attr("disabled", g.disabled);
        }
        if (g.name) {
            g.dom.field.attr("name", g.name);
        }
        if (g.submitValue) {
            g.dom.field.data('submitValue', g.submitValue);
        }
        g.dom.field.attr("name", g.name);
    },
    addEvents: function () {
        var g = this;
        g.dom.field.bind("click", function () {
            if (!g.dom.field.hasClass(g.focusCss)) {
                g.dom.field.addClass(g.focusCss);
            }
        });

        if (this.handler) {
            g.dom.field.bind("click", this.handler);
        }
        var listener = this.listener;
        if (listener) {
            for (var key in listener)
                g.dom.field.bind(key, listener[key]);
        }
    },

    sysValidater: function () {

    },
    keyup: function () {
        this.sysValidater();
    },

    getValue: function () {
        return this.dom.field.val();
    },
    initSubmitValue: function () {
        var g = this, value = {};
        if (g.field) {
            for (var i = 0; i < g.field.length; i++) {
                var name = g.field[i];
                value[name] = "";
            }
        }
        g.submitValue = value;
    },
    getSubmitValue: function () {
        var data = {};
        if (this.name)
            data[this.name] = this.getValue();
        EIAP.applyIf(data, this.submitValue);
        return data;
    },
    setSubmitValue: function () {
        var g = this, value = {};
        var data = arguments[0];
        if (data && g.field) {
            for (var i = 0; i < g.field.length; i++) {
                var name = g.field[i];
                value[name] = (data[name] != undefined && data[name] != null ? data[name] : "");
            }
        }
        g.submitValue = value;
    },
    loadData: function () {
        var data = arguments[0];
        this.setSubmitValue(data);
        if (data) {
            this.setValue(data[this.name]);
        }
    },
    setReadOnly: function () {
        var args = arguments;
        if (args.length != 0) {
            var arg = args[0] == "true" || args[0] == true ? true : false;
            this.dom.field.attr("readonly", arg);
            this.readonly = arg;
            if (arg) {
                if (!this.dom.field.hasClass(this.readonlyCss)) {
                    this.dom.field.addClass(this.readonlyCss);
                }
            } else {
                this.dom.field.removeClass(this.readonlyCss);
            }
        }
    },
    setWidth: function () {
        this.dom.field.width(arguments[0]);
    },
    setValue: function () {
        this.dom.field.val(arguments[0]);
    },
    reset: function () {
        this.dom.field.val("");
        this.initSubmitValue();
    },
    showTip: function () {
        EIAP.remove(this.tooltip);
        this.tooltip = EIAP.ToolTip({ target: this.dom.field, isInvalid: true, tipText: this.invalidText });
    }
});﻿EIAP.TextField = function () {
    return new EIAP.form.TextField(arguments[0]);
};

EIAP.form.TextField = EIAP.extend(EIAP.form.Field, {
    inputType: 'text',
    width: 160,
    height: 18,
    minlength: 0,
    maxlength: Number.MAX_VALUE,
    allowChar: null,
    allowBlank: true,
    validater: null,
    validateText: null,
    displayText: null,
    displayCss: "ux-field-display",
    fieldCss: "ux-field-text",
    focusCss: "ux-field-focus",
    fieldStyle: null,
    invalidCss: "ux-field-invalid",
    initComponent: function () {
        EIAP.form.TextField.superclass.initComponent.call(this);
    },
    __getType: function () {
        return 'TextField';
    },

    __idPrev: function () {
        return 'TextField';
    },

    _extMethods: function () {
        return EIAP.form.TextField;
    },
    _render: function () {
        EIAP.form.TextField.superclass._render.call(this);
        this.addFiledStyle();
    },
    initField: function () {
        EIAP.form.TextField.superclass.initField.call(this);
        this.setWidth(this.width);
        this.setHeight(this.height);
        this.initDisplayText();
    },
    initLabel: function () {
        var g = this;
        if (g.title) {
            var titleText = !g.labelFirst ? g.title : g.title + "：";
            titleText = !g.allowBlank ? (titleText + "<span class='" + g.requiredCss + "'>*</span>") : titleText;
            var label = $("<label>" + titleText + "</label>");
            if (g.showTitle) label.attr("title", g.getLabel());
            label.addClass(g.labelCss);
            g.dom.label = label;
            g.dom.append(label);
            g.setLabelWidth(g.labelWidth ? g.labelWidth : 70);
        }
    },
    setAllowBlank: function (v) {
        var g = this;
        if (v === false) {
            if (g.dom.label.find("span." + g.requiredCss).length > 0) return;
            g.dom.label.append("<span class='" + g.requiredCss + "'>*</span>");
            g.allowBlank = false;
        } else {
            g.dom.label.find("span." + g.requiredCss).remove();
            g.allowBlank = true;
        }
    },
    setWidth: function () {
        var width = parseInt(arguments[0]);
        if (width) {
            if (typeof arguments[0] == "string" && arguments[0].indexOf("%") > -1) {
                width /= 100;
                width *= this.dom.parent().width();
                if (this.dom.label) {
                    if (!this.labelWidth) {
                        if (width * 7 / 23 < 40) {
                            this.setLabelWidth(40);
                            width -= 40;
                        }
                        if (width * 7 / 23 > 70) {
                            this.setLabelWidth(70);
                            width -= 70;
                        } else {
                            this.setLabelWidth(width * 7 / 23);
                            width -= (width * 7 / 23);
                        }
                    } else {
                        this.setLabelWidth(this.labelWidth);
                        width -= this.labelWidth;
                    }
                }
                width -= 10;
            }
            this.dom.field.width(width);
            this.width = arguments[0];
        }
    },
    setHeight: function () {
        var height = parseInt(arguments[0]);
        if (height) {
            this.dom.field.height(height);
            this.dom.height(height + parseFloat(this.dom.css("marginBottom")));

        }
    },
    initDisplayText: function () {
        var g = this;
        if (g.displayText) {
            g.dom.field.val(g.displayText);
            g.dom.field.addClass(g.displayCss);
        }
    },
    addEvents: function () {
        var g = this;
        var field = g.dom.field;
        field.bind("keypress", function (e) {
            var code = e.keyCode || e.charCode;
            if (code == 37 || code == 39 || code == 46 || code == 8 || (e.ctrlKey && code > 0)) {
                if (e.ctrlKey && (code == 118 || code == 86)) {
                    g.sysValidater();
                }
                return true;
            } else {
                var chr = String.fromCharCode(code);
                if (g.allowChar && g.allowChar.indexOf(chr) == -1) {
                    return false;
                }
            }
        });
        field.hover(function () {
            if (!field.hasClass(g.invalidCss)) {
                field.addClass(g.focusCss);
            }
        }, function () {
            field.removeClass(g.focusCss);
        });
        field.bind("blur", function () {
            field.removeClass(g.focusCss);
        });
        if (g.displayText) {
            g.doDisplayEvents();
        } else {
            g.doBlankEvents();
        }
        EIAP.form.TextField.superclass.addEvents.call(this);
    },
    doDisplayEvents: function () {
        var g = this;
        g.dom.field.bind("blur", function () {
            var value = g.dom.field.val();
            if (!value) {
                g.dom.field.addClass(g.displayCss);
                g.dom.field.val(g.displayText);
                g.removeFiledStyle();
            }
            g.dom.field.removeClass(g.focusCss);
            g.sysValidater();
            g.dom.field.removeClass(g.focusCss);
        });
        g.dom.field.bind("keyup", function () {
            g.sysValidater();
        });
        g.dom.field.bind("click", function () {
            if (!g.readonly) {
                var value = g.dom.field.val();
                if (g.displayText == value) {
                    g.dom.field.val("");
                }
                g.dom.field.removeClass(g.displayCss);
                g.sysValidater();
            }
        });
    },
    doBlankEvents: function () {
        var g = this;
        g.dom.field.bind("keyup", function () {
            g.sysValidater();
        });
        g.dom.field.bind("blur", function () {
            g.sysValidater();
            g.dom.field.removeClass(g.focusCss);
        });
    },

    sysValidater: function () {
        var g = this;
        if (g.hidden)
            return true;
        var value = g.getValue();
        if (g.validater) {
            if (g.validater(value) == false) {
                g.invalidText = g.validateText ? g.validateText : "";
                g.afterValid(false);
                return false;
            }
        }
        if (g.allowChar && value.length > 0 && g.displayText != value) {
            for (var i = 0; i < value.length; i++) {
                var c = value.charAt(i);
                if (g.allowChar.indexOf(c) == -1) {
                    g.invalidText = String.format(g.invalidCharText, value, c);
                    g.afterValid(false);
                    return false;
                }
            }
        }
        if (!g.checkLength()) {
            g.afterValid(false);
            return false;
        }
        if (!g.allowBlank && (value == null || value === "" || g.displayText == value || value.length == 0)) {
            g.invalidText = g.blankText;
            g.afterValid(false);
            return false;
        }
        g.afterValid(true);
        return true;
    },
    afterValid: function () {
        var g = this, flag = arguments[0];
        if (!flag) {
            if (!g.dom.field.hasClass(g.invalidCss)) {
                g.dom.field.addClass(g.invalidCss);
                g.dom.field.removeClass(g.focusCss);
            }
            g.showTip();
        } else {
            g.dom.field.removeClass(g.invalidCss);
            g.dom.field.removeClass(g.focusCss);
            if (g.tooltip) {
                g.tooltip.close();
                g.tooltip = undefined;
            }
        }
    },
    checkLength: function () {
        var g = this;
        var value = g.dom.field.val();
        if (value.length < g.minlength) {
            g.invalidText = String.format(g.minLengthText, g.minlength);
            return false;
        }
        if (value.length > g.maxlength) {
            g.invalidText = String.format(g.maxLengthText, g.maxlength);
            return false;
        }
        return true;
    },
    addFiledStyle: function () {
        var g = this;
        if (g.fieldStyle) {
            var fcss = g.dom.field.attr("style");
            if (typeof g.fieldStyle == "string") {
                var curcss = EIAP.util.DomStyle.cssToObj(fcss);
                var tcss = EIAP.util.DomStyle.cssToObj(g.fieldStyle);
                var style = EIAP.apply(curcss, tcss);
                var cssStr = EIAP.util.DomStyle.objToCss(style);
                g.dom.field.attr("style", cssStr);
            }
        }
    },
    removeFiledStyle: function () {
        var g = this;
        if (g.fieldStyle) {
            var fcss = g.dom.field.attr("style");
            if (typeof g.fieldStyle == "string") {
                var curcss = EIAP.util.DomStyle.cssToObj(fcss);
                var tcss = EIAP.util.DomStyle.cssToObj(g.fieldStyle);
                var cssObj = EIAP.util.DomStyle.removeStyle(curcss, tcss);
                var cssStr = EIAP.util.DomStyle.objToCss(cssObj);
                g.dom.field.attr("style", cssStr);
            }
        }
    },
    getValue: function () {
        var g = this, v = g.dom.field.val();
        if (g.displayText === v) {
            return "";
        }
        return g.dom.field.val();
    },
    setValue: function () {
        var g = this;
        EIAP.form.TextField.superclass.setValue.call(this, arguments[0]);
        if (arguments.length != 0 && arguments[0]) {
            g.dom.field.removeClass(g.displayCss);
        } else {
            g.initDisplayText();
        }
    },
    onResize: function () {
        var g = this;
        if (typeof g.width == "string" && g.width.indexOf("%") > -1) {
            g.setWidth(g.width);
        }
    },
    reset: function () {
        var g = this;
        if (!g.displayText || g.displayText == "") {
            g.dom.field.val("");
        } else {
            g.initDisplayText();
        }
        this.initSubmitValue();
    }
});﻿EIAP.NumberField = function () {
    return new EIAP.form.NumberField(arguments[0]);
};

EIAP.form.NumberField = EIAP.extend(EIAP.form.TextField, {
    maxValue: Number.MAX_VALUE,
    minValue: Number.NEGATIVE_INFINITY,
    precision: 2,
    allowNegative: true,
    allowChar: "0123456789",

    initComponent: function () {
        EIAP.form.NumberField.superclass.initComponent.call(this);
        if (!this.allowNegative) {
            this.minValue = this.minValue > 0 ? this.minValue : 0;
        } else {
            this.allowChar += "-";
        }
        if (this.precision > 0) {
            this.allowChar += ".";
        }
    },
    __getType: function () {
        return 'NumberField';
    },

    __idPrev: function () {
        return 'NumberField';
    },

    _extMethods: function () {
        return EIAP.form.NumberField;
    },
    initField: function () {
        EIAP.form.NumberField.superclass.initField.call(this);
        this.dom.field.css({ "ime-mode": "disabled" });
    },
    addEvents: function () {
        var g = this;
        this.dom.field.bind("blur", function (e) {
            var value = g.getValue();
            if (!value) {
                value = 0;
                g.setValue(value.toFixed(this.precision));
                return;
            }
            if (g.precision >= 0) {
                if (isNaN(value)) {
                    value = g.getValue();
                }
                g.setValue(value);
            } else {
                throw new Error(g.negPrecision);
            }
        });
        EIAP.form.NumberField.superclass.addEvents.call(this);
    },

    sysValidater: function () {
        var g = this;
        var parent = EIAP.form.NumberField.superclass.sysValidater.call(this);
        if (!parent) {
            return false;
        } else {
            var value = EIAP.form.NumberField.superclass.getValue.call(this);
            if (value) {
                if (!$.isNumeric(value)) {
                    g.invalidText = g.notNumberText;
                    g.afterValid(false);
                    return false;
                }
            }
            if (!this.checkValue()) {
                g.afterValid(false);
                return false;
            }
        }
        return true;
    },
    checkValue: function () {
        var g = this;
        var value = g.getValue();
        if (!value) {
            value = 0;
        }
        if (value < g.minValue) {
            g.invalidText = String.format(g.minValueText, g.minValue);
            return false;
        }
        if (value > g.maxValue) {
            g.invalidText = String.format(g.maxValueText, g.maxValue);
            return false;
        }
        return true;
    },
    getValue: function () {
        var value = EIAP.form.NumberField.superclass.getValue.call(this);
        if (value)
            return parseFloat(value).toFixed(this.precision);
        else {
            value = 0;
            return value.toFixed(this.precision);
        }
    },
    setValue: function () {
        var v = arguments.length != 0 && arguments[0] && !isNaN(arguments[0]) && arguments[0] != "" ? arguments[0] : 0;
        v = parseFloat(v).toFixed(this.precision);
        EIAP.form.NumberField.superclass.setValue.call(this, v);
    }
});﻿EIAP.CheckBox = function () {
    return new EIAP.form.CheckBox(arguments[0]);
};

EIAP.form.CheckBox = EIAP.extend(EIAP.form.Field, {
    inputType: 'checkbox',
    fieldCss: "ux-field-checkbox",
    fieldWrapCss: "ux-checkbox",
    onChecked: null,
    checked: false,
    initComponent: function () {
        EIAP.form.CheckBox.superclass.initComponent.call(this);
    },
    __getType: function () {
        return 'CheckBox';
    },
    __idPrev: function () {
        return 'CheckBox';
    },
    _extMethods: function () {
        return EIAP.form.CheckBox;
    },
    initField: function () {
        var g = this;
        EIAP.form.CheckBox.superclass.initField.call(this);
        g.dom.fieldwrap.addClass(g.fieldWrapCss);
        var fieldicon = $('<span class="ux-icon"></span>');
        g.dom.field.hide();
        g.dom.fieldicon = fieldicon;
        g.dom.fieldwrap.append(fieldicon);
        if (g.checked) {
            g.setValue(true);
            g.dom.fieldicon.click();
        }
        if (g.readonly) {
            g.setReadOnly(g.readonly);
        }
    },
    addEvents: function () {
        var g = this;
        g.dom.fieldicon.bind("click", function () {
            if (!g.disabled) {
                if (g.checked) {
                    g.dom.field.attr("checked", false);
                    $(this).removeClass("checked");
                    g.checked = false;
                } else {
                    g.checked = true;
                    g.dom.field.attr("checked", true);
                    $(this).addClass("checked");
                }
                if (g.onChecked && g.onChecked instanceof Function) {
                    g.onChecked.call(g, g.getValue());
                }
            }
        });
        g.dom.label.bind("click", function () {
            g.dom.fieldicon.click();
        });
        g.dom.fieldwrap.hover(function () {
            if (!g.disabled) {
                $(this).addClass(g.fieldWrapCss + "-over");
            }
        }, function () {
            $(this).hasClass(g.fieldWrapCss + "-over") && $(this).removeClass(g.fieldWrapCss + "-over");
        });
    },
    addCss: function () {
    },
    getValue: function () {
        return this.checked;
    },
    getSubmitValue: function () {
        var data = {};
        if (this.name)
            data[this.name] = this.getValue();
        if (this.checked)
            EIAP.applyIf(data, this.submitValue);
        return data;
    },
    setValue: function (v) {
        var g = this;
        if (v != undefined) {
            v = v.toString().toLowerCase();
            if (v == "true") {
                g.dom.field.attr("checked", true);
                g.dom.fieldicon.addClass("checked");
                g.checked = true;
                if (g.disabled) {
                    g.dom.fieldwrap.addClass(g.fieldWrapCss + "-checked");
                }
            } else {
                g.checked = false;
                g.dom.field.attr("checked", false);
                g.dom.fieldicon.removeClass("checked");
                if (g.disabled) {
                    g.dom.fieldwrap.removeClass(g.fieldWrapCss + "-checked");
                }
            }
        }
    },
    sysValidater: function () {
        return true;
    },
    setReadOnly: function () {
        var args = arguments;
        if (args.length != 0) {
            var arg = args[0] == "true" || args[0] == true ? true : false;
            if (arg) {
                this.dom.fieldicon.addClass("disabled");
                this.disabled = true;
                this.checked && this.dom.fieldwrap.addClass(this.fieldWrapCss + "-checked");
            } else {
                this.disabled = false;
                this.dom.fieldicon.removeClass("disabled");
                this.dom.fieldwrap.hasClass(this.fieldWrapCss + "-checked") && this.dom.fieldwrap.removeClass(this.fieldWrapCss + "-checked");
            }
        }
    },
    reset: function () {
        var g = this;
        g.dom.field.attr("checked", false);
        g.dom.fieldicon.removeClass("checked");
        g.dom.fieldwrap.removeClass(g.fieldWrapCss + "-checked");
        g.checked = false;
    }
});﻿EIAP.RadioBox = function () {
    return new EIAP.form.RadioBox(arguments[0]);
};

EIAP.form.RadioBox = EIAP.extend(EIAP.form.CheckBox, {
    inputType: 'radio',
    labelFirst: false,
    inputValue: '',
    fieldCss: "ux-field-radiobox",
    fieldWrapCss: "ux-radiobox",
    initComponent: function () {
        EIAP.form.RadioBox.superclass.initComponent.call(this);
    },
    __getType: function () {
        return 'RadioBox';
    },
    __idPrev: function () {
        return 'RadioBox';
    },
    _extMethods: function () {
        return EIAP.form.RadioBox;
    },
    _render: function () {
        var g = this;
        EIAP.form.RadioBox.superclass._render.call(this);
        g.inputValue = g.inputValue == "" ? g.id : g.inputValue;
        g.dom.field.val(g.inputValue);
        if (this.checked) {
            g.setValue(g.inputValue);
            g.dom.fieldicon.click();
        }
        if (g.readonly) {
            g.setReadOnly(g.readonly);
        }
    },
    addEvents: function () {
        var g = this;
        g.dom.fieldicon.bind("click", function () {
            if (!$(this).hasClass("disabled")) {
                g.dom.field.attr("checked", true);
                $(this).addClass("checked");
                g.checked = true;
                if (g.onChecked && g.onChecked instanceof Function) {
                    g.onChecked.call(g, g.getValue());
                }
            }
        });
        g.dom.label.bind("click", function () {
            g.dom.fieldicon.click();
        });
        g.dom.fieldwrap.hover(function () {
            if (!g.dom.fieldicon.hasClass("disabled")) {
                $(this).addClass(g.fieldWrapCss + "-over");
            }
        }, function () {
            $(this).hasClass(g.fieldWrapCss + "-over") && $(this).removeClass(g.fieldWrapCss + "-over");
        });
    },
    getValue: function () {
        return this.checked && this.dom.field.val();
    },
    setValue: function (v) {
        var g = this;
        if (!$(this).hasClass("checked") && g.getValue() == v) {
            g.dom.field.attr("checked", true);
            g.checked = true;
            g.dom.fieldicon.addClass("checked");
            if (g.dom.fieldicon.hasClass("disabled")) {
                g.dom.fieldwrap.addClass(g.fieldWrapCss + "-checked");
            } else {
                g.dom.fieldwrap.removeClass(g.fieldWrapCss + "-checked");
            }
        }
    },
    getSubmitValue: function () {
        if (this.checked) {
            var data = {};
            if (this.name)
                data[this.name] = this.getValue();
            EIAP.applyIf(data, this.submitValue);
            return data;
        }
        return "";
    },
    setReadOnly: function () {
        var args = arguments;
        if (args.length != 0) {
            var arg = args[0] == "true" || args[0] == true ? true : false;
            if (arg) {
                this.dom.fieldicon.addClass("disabled");
                this.disabled = true;
                this.dom.field.attr("checked") && this.dom.fieldwrap.addClass(this.fieldWrapCss + "-checked");
            } else {
                this.dom.fieldicon.removeClass("disabled");
                this.disabled = false;
                this.dom.fieldwrap.hasClass(this.fieldWrapCss + "-checked") && this.dom.fieldwrap.removeClass(this.fieldWrapCss + "-checked");
            }
        }
    },
    reset: function () {
        EIAP.form.RadioBox.superclass.reset.call(this);
        this.dom.fieldwrap.removeClass(this.fieldWrapCss + "-checked");
    }
});﻿EIAP.CheckBoxGroup = function () {
    return new EIAP.form.CheckBoxGroup(arguments[0]);
};

EIAP.form.CheckBoxGroup = EIAP.extend(EIAP.form.TextField, {
    onChecked: null,
    itemAlign: 'h',
    isFormField: true,
    defaultStyle: null,
    onlyOneChecked: false,
    wrapCls: 'ux-checkbox-wrap',
    itemCls: 'ux-checkbox-item',
    invalidCls: 'ux-checkbox-invalid',
    initComponent: function () {
        EIAP.form.CheckBoxGroup.superclass.initComponent.call(this);
    },

    __getType: function () {
        return 'CheckBoxGroup';
    },
    __idPrev: function () {
        return 'CheckBoxGroup';
    },
    _extMethods: function () {
        return EIAP.form.CheckBoxGroup;
    },
    _render: function () {
        var g = this;
        g.dom = g.renderTo ? $(this.element) : $("<div></div>");
        g.dom.addClass("ux-field");
        g.initLabel();
        g.addEvents();
        g.set(g);
    },
    setCmpType: function (cfg) {
        return EIAP.CheckBox(cfg);
    },
    addItems: function () {
        var g = this, items = this.options.items;
        if (items && g.dom) {
            var pleft = g.title ? g.dom.label.width() : 2;
            g.dom.fieldwrap = $("<div></div>").addClass(g.wrapCls).css("padding-left", pleft);
            g.dom.append(g.dom.fieldwrap);
            for (var i = 0; i < items.length; i++) {
                if (g.onChecked) {
                    items[i].onChecked = g.onChecked;
                }
                if (g.readonly) {
                    items[i].readonly = g.readonly;
                }
                items[i].isFormField = !g.isFormField;
                EIAP.applyIf(items[i], this.defaultStyle);
                var cmp = g.setCmpType(items[i]);
                if (g.itemAlign == "h") {
                    cmp.dom.addClass(g.itemCls);
                }
                g.dom.fieldwrap.append(cmp.dom);
                this.items.push(cmp.id);
            }
            g.dom.fieldwrap.append("<div class='ux-clear'></div>");
            g.onlyOneChecked && g.initGroupEvent();
        }
    },
    initGroupEvent: function () {
        var g = this;
        g.dom.fieldwrap.children("div.ux-field").each(function () {
            var rbox = EIAP.get($(this).attr("eiapuiid"));
            rbox.dom.fieldicon.bind("click", function () {
                if (!rbox.disabled) {
                    for (var m = 0; m < g.items.length; m++) {
                        var item = EIAP.getCmp(g.items[m]);
                        if (rbox.id != item.id) {
                            item.reset();
                        }
                    }
                }
            });
        });
    },
    loadData: function () {
        this.reset();
        EIAP.form.CheckBoxGroup.superclass.loadData.call(this, arguments[0]);
    },
    setReadOnly: function () {
        var g = this, args = arguments;
        if (args.length != 0) {
            var arg = args[0] == "true" || args[0] == true ? true : false;
            for (var i = 0; i < g.items.length; i++) {
                var item = EIAP.getCmp(g.items[i]);
                item.setReadOnly(arg);
            }
        }
    },
    setSubmitValue: function () {
    },
    getSubmitValue: function () {
        if (!this.name)
            throw new Error(String.format(EIAP.error.noName, this.type));
        var data = {}, arr = [];
        for (var i = 0; i < this.items.length; i++) {
            var item = EIAP.getCmp(this.items[i]);
            if (item.checked) {
                var itemData = {};
                if (item.name)
                    itemData[item.name] = item.getValue();
                EIAP.applyIf(itemData, item.submitValue);
                arr.push(itemData);
            }
        }
        data[this.name] = arr;
        return data;
    },
    sysValidater: function () {
        var g = this;
        if (!g.allowBlank) {
            for (var i = 0; i < g.items.length; i++) {
                if (EIAP.getCmp(g.items[i]).checked) {
                    if (this.tooltip) {
                        this.tooltip.close();
                        this.tooltip = undefined;
                    }
                    g.dom.fieldwrap.removeClass(g.invalidCls);
                    return true;
                }
            }
            g.dom.fieldwrap.addClass(g.invalidCls);
            g.invalidText = g.validateText ? g.validateText : g.blankText;
            g.showTip();
            return false;
        }
        return true;
    },
    reset: function () {
        var g = this;
        for (var i = 0; i < g.items.length; i++) {
            EIAP.getCmp(g.items[i]).reset();
        }
    },
    showTip: function () {
        this.tooltip = EIAP.ToolTip({ target: this.dom.fieldwrap, isInvalid: true, tipText: this.invalidText });
    },
    addEvents: function () {
    }
});﻿EIAP.RadioBoxGroup = function () {
    return new EIAP.form.RadioBoxGroup(arguments[0]);
};

EIAP.form.RadioBoxGroup = EIAP.extend(EIAP.form.CheckBoxGroup, {
    onChecked: null,
    itemAlign: 'h',
    isFormField: false,
    defaultStyle: null,
    onlyOneChecked: true,
    wrapCls: 'ux-radiobox-wrap',
    itemCls: 'ux-radiobox-item',
    invalidCls: 'ux-radiobox-invalid',
    initComponent: function () {
        EIAP.form.RadioBoxGroup.superclass.initComponent.call(this);
    },

    __getType: function () {
        return 'RadioBoxGroup';
    },
    __idPrev: function () {
        return 'RadioBoxGroup';
    },
    _extMethods: function () {
        return EIAP.form.RadioBoxGroup;
    },
    setCmpType: function (cfg) {
        return EIAP.RadioBox(cfg);
    }
});﻿EIAP.TextArea = function () {
    return new EIAP.form.TextArea(arguments[0]);
};

EIAP.form.TextArea = EIAP.extend(EIAP.form.TextField, {
    width: 160,
    height: 60,
    autoHeight: false,
    initComponent: function () {
        EIAP.form.TextArea.superclass.initComponent.call(this);
    },
    __getType: function () {
        return 'TextArea';
    },

    __idPrev: function () {
        return 'TextArea';
    },

    _extMethods: function () {
        return EIAP.form.TextArea;
    },

    initField: function () {
        var g = this;
        var textarea = $("<textarea></textarea>");
        textarea.addClass("ux-field-textarea");
        g.dom.field = textarea;
        var div = $("<div class='ux-field-element'></div>");
        div.append(g.dom.field);
        g.dom.append(div).append("<div class='ux-clear'> </div>");
        g.setWidth(g.width);
        g.setHeight(g.height);
        g.initDisplayText();
    },
    loadData: function () {
        EIAP.form.TextArea.superclass.loadData.call(this, arguments[0]);
        if (this.autoHeight) {
            var h = this.dom.field[0].scrollHeight - parseFloat(this.dom.field.css("borderTopWidth")) - parseFloat(this.dom.field.css("borderBottomWidth"));
            if (h > this.height) {
                this.dom.height(h + 4);
                this.dom.field.height(h);
            }
        }
    }
});﻿EIAP.TriggerField = function () {
    return new EIAP.form.TriggerField(arguments[0]);
};
EIAP.form.TriggerField = EIAP.extend(EIAP.form.TextField, {
    editable: false,
    canClear: true,
    shadow: true,
    loadonce: true,
    beforeSelect: null,
    afterSelect: null,
    listCss: "ux-list",
    triggerCss: "ux-trigger",
    clearTriggerCss: "ux-clear-trigger",
    triggerHoverCss: "ux-trigger-hover",
    triggerClickCss: "ux-trigger-click",
    triggerDisableCss: "ux-trigger-disable",
    multiBoxCls: "ux-list-multibox",
    reader: null,
    afterClear: null,
    cascadeCfg: null,
    initComponent: function () {
        EIAP.form.TriggerField.superclass.initComponent.call(this);
        this.initReader();
        this.loading = false;
    },
    __getType: function () {
        return 'TriggerField';
    },

    __idPrev: function () {
        return 'TriggerField';
    },

    _extMethods: function () {
        return EIAP.form.TriggerField;
    },

    initField: function () {
        EIAP.form.TriggerField.superclass.initField.call(this);
        this.dom.field.attr("eiapuiid", this.id);
        if (!this.editable) {
            this.dom.field.attr("readonly", true);
            this.dom.field.addClass("ux-hand");
        }
        this.initTrigger();
        if (this.readonly) {
            this.setReadOnly(true);
        }
    },
    setWidth: function () {
        var width = parseInt(arguments[0]);
        if (width) {
            if (typeof arguments[0] == "string" && arguments[0].indexOf("%") > -1) {
                width /= 100;
                width *= this.dom.parent().width();
                if (this.dom.label) {
                    if (!this.labelWidth) {
                        if (width * 7 / 23 < 40) {
                            this.setLabelWidth(40);
                            width -= 40;
                        }
                        if (width * 7 / 23 > 70) {
                            this.setLabelWidth(70);
                            width -= 70;
                        } else {
                            this.setLabelWidth(width * 7 / 23);
                            width -= (width * 7 / 23);
                        }
                    } else {
                        this.setLabelWidth(this.labelWidth);
                        width -= this.labelWidth;
                    }
                }
                if (this.dom.clearTrigger && this.dom.clearTrigger.is(":visible")) {
                    width -= 17;
                }
                width -= 10;
            }
            width -= 17;
            this.dom.field.width(width);
            this.width = arguments[0];
        }
    },
    setHeight: function () {
        var height = parseInt(arguments[0]);
        if (height) {
            this.dom.field.height(height);
        }
    },
    setValue: function () {
        var g = this, args = arguments[0];
        EIAP.form.TriggerField.superclass.setValue.call(this, args);
        if (g.canClear && !g.readonly) {
            if (!g.dom.triggerbtn.hasClass(g.triggerDisableCss)) {
                args && args.length > 0 && g.showClear();
            } else {
                g.hideClear();
            }
        }
    },
    initTrigger: function () {
        var g = this;
        var triggerbtn = $('<img src="' + EIAP.BLANK_IMAGE_URL + '" />');
        triggerbtn.addClass(g.triggerCss);
        triggerbtn.attr("eiapuiid", g.id);
        g.dom.triggerbtn = triggerbtn;
        g.dom.field.after(triggerbtn);
        if (g.canClear) {
            g.dom.clearTrigger = $('<img src="' + EIAP.BLANK_IMAGE_URL + '" class="' + g.clearTriggerCss + '" />');
            g.dom.field.after(g.dom.clearTrigger);
            g.clear = true;
            g.dom.clearTrigger.bind("click", function () {
                g.reset();
                g.hideClear();
                g.afterClear && g.afterClear.call(g);
            });
        }
    },
    showClear: function () {
        var g = this;
        if (g.canClear && g.clear) {
            var iptw = g.dom.field.width();
            g.dom.field.width(iptw - 17);
            g.dom.clearTrigger.show();
            g.clear = false;
        }
    },
    hideClear: function () {
        var g = this;
        if (g.canClear && !g.clear) {
            var iptw = g.dom.field.width();
            g.dom.clearTrigger.hide();
            g.dom.field.width(iptw + 17);
            g.clear = true;
        }
    },
    addEvents: function () {
        var g = this;
        g.dom.field.bind("click", function () {
            if (!g.readonly)
                g.onClick();
        }).bind("keydown", function (e) {
            if (!g.editable) {
                e.returnValue = false;
                return false;
            }
        });
        g.dom.triggerbtn.bind("click", function () {
            if (!g.readonly)
                g.onClick();
        });
        g.dom.triggerbtn.hover(function () {
            if (!g.readonly || !$(this).hasClass(g.triggerDisableCss)) {
                $(this).addClass("ux-trigger-over");
            }
        }, function () {
            $(this).hasClass("ux-trigger-over") && $(this).removeClass("ux-trigger-over");
        });
        if (g.dom.clearTrigger) {
            g.dom.clearTrigger.hover(function () {
                $(this).addClass("ux-trigger-over");
            }, function () {
                $(this).removeClass("ux-trigger-over");
            });
        }
        EIAP.form.TriggerField.superclass.addEvents.call(this);
    },
    setReadOnly: function () {
        var g = this, args = arguments;
        if (args.length != 0) {
            EIAP.form.TriggerField.superclass.setReadOnly.call(this, args[0]);
            if (args[0] == "true" || args[0] == true) {
                g.dom.triggerbtn.addClass(g.triggerDisableCss);
                g.hideClear();
            } else {
                g.dom.triggerbtn.removeClass(g.triggerDisableCss);
            }
            if (!g.editable) {
                g.dom.field.attr("readonly", true);
            }
        }
    },
    hideOther: function () {
        var g = this;
        $(document).bind("click", function (evt) {
            if (evt.button == 2) {
                return;
            }
            var el = evt.target;
            if (el) {
                var eiapid = $(el).parent().attr("eiapuiid");
                if ($(el).hasClass("ux-field-element") && eiapid == g.id) {
                    return;
                }
                var parent = $(el).parent();
                eiapid = parent.parent().attr("eiapuiid");
                if (parent.hasClass("ux-field-element") && eiapid == g.id) {
                    return;
                }
                if (parent.hasClass("ux-field-element") && parent.parents().hasClass("ux-combo-list-item") || parent.hasClass("ux-field-element") && parent.parents().hasClass("ux-toolbar") || parent.hasClass("ux-combo-list-inner") || el.localName == "label" || $(el).hasClass("ux-checkbox")) {
                    return;
                }
            }
            g.hideList();
        }).bind("scroll", function () {
            g.hideList();
        });
        if (g.parentCmp) {
            var pcmp = EIAP.getCmp(g.parentCmp);
            pcmp.dom.parentsUntil("ux-panel-content,ux-window-content").bind("scroll", function () {
                g.hideList();
            });
        }
    },
    onClick: function () {
        var g = this;
        if (!g.dom.triggerbtn.hasClass(g.triggerDisableCss)) {
            if (!g.dom.triggerbtn.hasClass(g.triggerCss))
                g.dom.triggerbtn.addClass(g.triggerCss);
            if (!g.dom.field.hasClass(g.focusCss)) {
                g.dom.field.addClass(g.focusCss);
            }
            g.dom.triggerbtn.addClass(g.triggerClickCss);
            this.showList();
            g.hideOther();
        }
    },
    addLoadMask: function () {
        var g = this;
        var load = $('<div class="ux-combo-list-loading"></div>');
        load.html(EIAP.LoadingMask.prototype.msg);
        g.list.loadMask = load;
        g.list.append(load);
    },
    removeLoadMask: function () {
        this.list.loadMask.remove();
    },
    initReader: function () {
        var g = this, sysReader = {};
        var rfield = g.field, name = g.name;
        if (g.reader) {
            name = g.reader ? g.reader.name : name;
            if (g.reader.field) {
                if (g.reader.field.length != g.field.length) {
                    throw new Error(EIAP.error.neqField);
                }
                rfield = g.reader.field;
            }
            var field = EIAP.util.Array.union([name], rfield);
            sysReader.mixField = field;
        }
        sysReader.name = name;
        sysReader.field = rfield;
        g.sysReader = sysReader;
    },
    initList: function () {
        var g = this;
        var timestamp = new Date().getTime();
        g.timeStamp = timestamp;
        var list = $('<div></div>');
        list.attr("eiapuiid", g.id).addClass(g.listCss);
        g.list = list;
        g.addLoadMask();
        $("body").append(list);
        g.setListPos();
        g.showShadow();
        g.loading = true;
        if (!g.data) {
            if (g.store) {
                g.fireEvent('beforeLoad', this);
                g.store.load({
                    success: function (response) {
                        if (g.timeStamp == timestamp) {
                            if (!response.data) {
                                g.list.html(g.dataFormError);
                                return;
                            }
                            g.data = response.data;
                            g.fireEvent('afterLoad', response.data);
                            g.showComboList();
                        }
                    }
                });
            } else {
                throw new Error(EIAP.error.dataError);
            }
        } else {
            g.showComboList();
        }
    },
    showComboList: function () {
        var g = this, data = g.data;
        g.removeLoadMask();
        var sv = g.getValue();
        g.listbox = $('<div eiapuiid="' + g.id + '" class="' + g.listInner + '"></div>');
        g.list.append(g.listbox);
        g.addListItem(data, sv);
    },
    addListItem: function (data, sv) {
        var g = this;
        g.removeChkCmps();
        g.chkCmps = [];
        var txt = $("<span style='color:gray;line-height:20px;'>" + g.emptyText + "</span>");
        g.listbox.empty();
        for (var i = 0; i < data.length; i++) {
            var itemValue = data[i];
            var name = g.sysReader.name;
            if (g.multiSelect) {
                var chkCmp = EIAP.CheckBox({
                    title: itemValue[name],
                    labelFirst: false,
                    showTitle: true,
                    itemData: itemValue,
                    onChecked: function (v) {
                        if (!v) {
                            g.chkAllCmpId && EIAP.getCmp(g.chkAllCmpId).setValue("false");
                            this.dom.removeClass(g.seletedCss);
                        } else {
                            this.dom.addClass(g.seletedCss);
                        }
                    }
                });
                g.chkCmps.push(chkCmp.id);
                chkCmp.dom.css({
                    margin: "0",
                    padding: "0 0 0 6px",
                    cursor: "default"
                }).addClass(g.listItemCss);
                chkCmp.dom.label.css({
                    cursor: "pointer"
                });
                g.listbox.append(chkCmp.dom);
            } else {
                var item = $("<div>" + itemValue[name] + "</div>");
                item.addClass(g.listItemCss);
                item.data("itemdata", itemValue);
                if (itemValue[name] == sv) {
                    item.addClass(g.seletedCss);
                }
                g.listbox.append(item);
            }
        }
        if (!(data instanceof Array) || data instanceof Array && data.length == 0) {
            g.listbox.append(txt);
        }
        g.addListItemEvent();
        g.loading = false;
        g.dom.triggerbtn.addClass(g.triggerClickCss);
        g.setListPos();
        g.showShadow();
    },
    showList: function () {
        var g = this;
        if (g.cascadeCfg) {
            g.updatePostParam();
            g.remove();
            g.initList();
        } else if (!g.loadonce) {
            g.remove();
            g.initList();
        } else {
            if (g.loading || g.list) {
                g.list.show();
                g.setListPos();
                g.showShadow();
            } else {
                g.initList();
            }
        }
    },
    //级联更新请求参数
    updatePostParam: function () {
        this.store.params = EIAP.apply(this.store.params || {}, this.getCascadeParams());
    },
    setListPos: function () {
        var g = this;
        var iptpos = g.dom.field.offset();
        var ipth = g.dom.field.outerHeight();
        var top = iptpos.top + ipth;
        var listh = g.list.height();
        if ($(window).height() <= (listh + top)) {
            var tmp = (iptpos.top - ipth - listh + 20);
            if (tmp > 0) {
                top = tmp;
            }
        }
        var tw = 0;
        $('img', g.dom).each(function () {
            if ($(this).is(":visible"))
                tw += 17;
        });
        var width = g.dom.field.width() + tw + 6;
        width = g.listWidth ? g.listWidth : width < 120 ? 120 : width;
        g.list.css({
            "left": iptpos.left,
            "top": top,
            "width": width
        }).show();
        g.shadow && g.dom.shadow && g.dom.shadow.updateShadow(g.list);
    },
    hideList: function () {
        var g = this;
        g.dom.triggerbtn && g.dom.triggerbtn.removeClass(g.triggerClickCss);
        g.list && g.list.hide();
        g.shadow && g.dom.shadow && g.dom.shadow.hide();
    },
    showShadow: function () {
        var g = this;
        if (g.shadow && EIAP.Shadow && !g.dom.shadow) {
            g.dom.shadow = new EIAP.Shadow({ target: g.list });
            g.items.push(g.dom.shadow.id);
            g.dom.shadow.updateShadow(g.list);
        }
    },
    remove: function () {
        var g = this;
        if (g.list) {
            g.list.remove();
            g.shadow && !g.dom.shadow && g.dom.shadow.remove();
            for (var i = 0; i < g.items.length; i++) {
                if (g.items[i] == g.dom.shadow)
                    g.items.splice(i, 1);
            }
            g.list = null;
            g.loading = false;
            if (g.store) {
                g.data = null;
            }
        }
    },
    reset: function () {
        var g = this;
        EIAP.form.TriggerField.superclass.reset.call(this);
        if (g.canClear && !g.clear) {
            var iptw = g.dom.field.width();
            g.dom.clearTrigger.hide();
            g.dom.field.width(iptw + 17);
            g.clear = true;
        }
    },
    getCascadeParams: function () {
        var g = this, tmpPostData = {};
        if (g.cascadeCfg && g.cascadeCfg instanceof Array) {
            for (var i = 0; i < g.cascadeCfg.length; i++) {
                if (!g.cascadeCfg[i].cmpId && !g.cascadeCfg[i].cmpName) {
                    continue;
                }
                var cmp = null;
                if (g.cascadeCfg[i].cmpId) {
                    cmp = EIAP.getCmp(g.cascadeCfg[i].cmpId);
                } else if (g.cascadeCfg[i].cmpName && g.parentCmp) {
                    var frmCmp = EIAP.getCmp(g.parentCmp);
                    if (!frmCmp.isFormField && !(frmCmp instanceof EIAP.panel.FormPanel)) {
                        frmCmp = EIAP.getCmp(frmCmp.parentCmp);
                    }
                    if (frmCmp instanceof EIAP.panel.FormPanel) {
                        cmp = frmCmp.getCmpByName(g.cascadeCfg[i].cmpName);
                    }
                }
                if (cmp instanceof EIAP.form.Field) {
                    for (var m = 0; m < g.cascadeCfg[i].field.length; m++) {
                        var tmpfdstr = g.cascadeCfg[i].field[m];
                        var tmpfd = tmpfdstr.split(":");
                        if (tmpfd.length == 2) {
                            var vd = cmp.getSubmitValue(), v = vd[tmpfd[1]];
                            if (v instanceof Array) {
                                tmpPostData[tmpfd[0]] = Object();
                                for (var k = 0; k < v.length; k++) {
                                    tmpPostData[tmpfd[0]][k] = v[k];
                                }
                            } else {
                                tmpPostData[tmpfd[0]] = v;
                            }
                        }
                    }
                }
            }
        }
        return tmpPostData;
    }
});﻿EIAP.ComboBox = function () {
    return new EIAP.form.ComboBox(arguments[0]);
};
EIAP.form.ComboBox = EIAP.extend(EIAP.form.TriggerField, {
    data: null,
    async: true,
    store: null,
    editable: false,
    loadMask: true,
    showSearch: false,
    searchWidth: 160,
    multiSelectWidth: 175,
    minListWidth: 0,
    searchText: null,
    beforeLoad: null,
    afterLoad: null,
    multiSelect: false,
    listInner: "ux-combo-list-inner",
    listItemCss: "ux-combo-list-item",
    seletedCss: "ux-combo-item-selected",
    initComponent: function () {
        EIAP.form.ComboBox.superclass.initComponent.call(this);
        if (this.beforeLoad) {
            this.on('beforeLoad', this.beforeLoad);
        }
        if (this.afterLoad) {
            this.on('afterLoad', this.afterLoad);
        }
        if (this.readonly) {
            this.async = true;
        }
        if (this.store)
            this.initStore();
    },
    __getType: function () {
        return 'ComboBox';
    },

    __idPrev: function () {
        return 'ComboBox';
    },

    _extMethods: function () {
        return EIAP.form.ComboBox;
    },
    addListItemEvent: function () {
        var g = this;
        if (g.multiSelect) return;
        $("." + g.listItemCss, g.list).each(function () {
            var item = $(this);
            item.bind("click", function (t) {
                var value = $(this).data("itemdata");
                if (g.beforeSelect) {
                    var before = {};
                    before.oldText = g.getValue();
                    before.oldValue = g.getSubmitValue();
                    before.data = value;
                    if (g.beforeSelect(before) == false) {
                        g.hideList();
                        return;
                    }
                }
                g.selectData(value);
                g.sysValidater();
                g.showClear();
                g.hideList();
                $(this).addClass(g.seletedCss).siblings().removeClass(g.seletedCss);
                if (g.afterSelect) {
                    var after = {};
                    after.text = g.getValue();
                    after.value = g.getSubmitValue();
                    after.data = value;
                    g.afterSelect(after);
                }
            });
        });
    },
    selectData: function () {
        var g = this, cmpCmp;
        var name = g.sysReader.name, data = arguments[0], value, i, chkCmp = null;
        if (g.chkCmpId) {
            chkCmp = EIAP.getCmp(g.chkCmpId);
        }
        if (!g.multiSelect) {
            g.setValue(data[name]);
        } else {
            value = [];
            if (g.chkCmps) {
                for (var m = 0; m < g.chkCmps.length; m++) {
                    cmpCmp = EIAP.getCmp(g.chkCmps[m]);
                    if (cmpCmp.checked) {
                        value.push(cmpCmp.itemData[name]);
                        if (chkCmp && chkCmp.checked) {
                            var curd = g.getValue();
                            for (var a = 0; a < value.length; a++) {
                                $.inArray(value[a], curd) < 0 && curd.push(value[a]);
                            }
                            value = curd;
                        }
                    }
                }
            }
            if (value.length == 0 && chkCmp && chkCmp.checked) {
                value = g.getValue();
            }
            g.setValue(value.toString());
        }
        if (g.field) {
            var rfield = g.sysReader.field, rname;
            value = {};
            if (g.multiSelect) {
                if (g.chkCmps) {
                    var idx = 0;
                    for (i = 0; i < g.chkCmps.length; i++) {
                        cmpCmp = EIAP.getCmp(g.chkCmps[i]);
                        if (cmpCmp.checked) {
                            data = cmpCmp.itemData;
                            for (var j = 0; j < g.field.length; j++) {
                                rname = rfield[j];
                                name = g.field[j];
                                if (idx == 0) {
                                    value[name] = [];
                                }
                                idx++;
                                value[name].push(data[rname].toString() ? data[rname] : "");
                            }
                        }
                    }
                    if (chkCmp && chkCmp.checked) {
                        var sv = g.submitValue;
                        for (var fn = 0; fn < g.field.length; fn++) {
                            name = g.field[fn];
                            if (!value[name]) continue;
                            for (var cv = 0; cv < value[name].length; cv++) {
                                if (typeof sv[name] == "string") {
                                    sv[name] = [];
                                }
                                $.inArray(value[name][cv], sv[name]) < 0 && sv[name].push(value[name][cv]);
                            }
                        }
                        value = sv;
                    }
                }
                var objnum = 0;
                for (var o in value) { objnum++; }
                if (objnum.length == 0 && chkCmp && chkCmp.checked) {
                    value = g.submitValue;
                }
            } else {
                for (i = 0; i < g.field.length; i++) {
                    rname = rfield[i];
                    name = g.field[i];
                    value[name] = data[rname] != undefined && data[rname] != null ? data[rname] : "";
                }
            }
            g.submitValue = value;
        }
    },
    checkedAll: function (v) {
        var g = this;
        if (g.chkCmps) {
            for (var i = 0; i < g.chkCmps.length; i++) {
                var cmp = EIAP.getCmp(g.chkCmps[i]);
                cmp.setValue(v.toString());
                v ? cmp.dom.addClass(g.seletedCss) : cmp.dom.removeClass(g.seletedCss);
            }
        }
    },
    initStore: function () {
        var g = this;
        g.store.autoLoad = !g.async;
        g.store.success = function (response) {
            g.data = response.data;
            g.fireEvent('afterLoad', response.data);
        };
        if (!g.async) {
            g.fireEvent('beforeLoad', g.store);
        }
        g.store.params = EIAP.apply(g.store.params || {}, g.getCascadeParams());
        var store = EIAP.Store(g.store);
        g.store = store;
    },
    showComboList: function () {
        var g = this;
        EIAP.form.ComboBox.superclass.showComboList.call(g);
        if (g.showSearch || g.multiSelect) {
            var barid = g.id + "_tbar";
            var barDom = $("<div></div>").attr("id", barid);
            g.list.prepend(barDom);
            var barCfg = {
                renderTo: barid,
                items: []
            };
            if (g.multiSelect) {
                g.chkCmpId = EIAP.getId("CheckBox");
                g.chkAllCmpId = EIAP.getId("CheckBox");
                var selllchk = {
                    xtype: "CheckBox",
                    id: g.chkAllCmpId,
                    labelWidth: 30,
                    labelFirst: false,
                    title: g.tSelectAll,
                    onChecked: function (v) {
                        g.checkedAll(v);
                    }
                };
                var appchk = {
                    xtype: "CheckBox",
                    id: g.chkCmpId,
                    labelWidth: 30,
                    labelFirst: false,
                    title: g.tAppend
                };
                barCfg.items.push(selllchk, "-", appchk, {
                    title: EIAP.cmpText.ok,
                    handler: function () {
                        if (g.beforeSelect) {
                            var before = {};
                            before.oldText = g.getValue();
                            before.oldValue = g.getSubmitValue();
                            if (g.beforeSelect(before) == false) {
                                g.hideList();
                                return;
                            }
                        }
                        g.selectData();
                        g.sysValidater();
                        g.showClear();
                        g.hideList();
                        if (g.afterSelect) {
                            var after = {};
                            after.text = g.getValue();
                            after.value = g.getSubmitValue();
                            g.afterSelect(after);
                        }
                    },
                    iconCls: 'icon-ok'
                });
                g.minListWidth = g.multiSelectWidth;
            }
            if (g.showSearch) {
                var cfg = {
                    xtype: "SearchBox",
                    id: g.id + "_search",
                    name: 'searchcmp' + g.id,
                    width: g.searchWidth,
                    displayText: g.searchText,
                    onSearch: function (v) {
                        g.filter(v);
                    }
                };
                barCfg.items.push(cfg);
                g.minListWidth += g.searchWidth + 15;
            }
            g.setListWidth();
            g.tbarCmp = EIAP.ToolBar(barCfg);
            g.setListPos();
            g.showShadow();
        }
    },
    setListWidth: function () {
        var g = this;
        if (!g.listWidth || g.listWidth < g.minListWidth) {
            g.listWidth = g.minListWidth;
        }
        if (g.chkCmps) {
            var w = g.listWidth - 45;
            for (var i = 0; i < g.chkCmps.length; i++) {
                var cmp = EIAP.getCmp(g.chkCmps[i]);
                cmp.setLabelWidth(w);
            }
        }
    },
    filter: function (v) {
        var g = this, datas = [];
        if (g.data && v) {
            for (var i = 0; i < g.data.length; i++) {
                var name = g.reader ? g.reader.name : g.name;
                if (name && g.data[i][name].indexOf(v) != -1) {
                    datas.push(g.data[i]);
                }
            }
        } else {
            datas = datas.concat(g.data);
        }
        g.addListItem(datas);
        g.setListWidth();
    },
    getValue: function () {
        var value = EIAP.form.ComboBox.superclass.getValue.call(this);
        if (this.multiSelect) {
            if (!value) {
                value = [];
            } else {
                value = value.split(",");
            }
        }
        return value;
    },
    removeChkCmps: function () {
        var g = this;
        if (g.chkCmps) {
            for (var r = 0; r < g.chkCmps.length; r++) {
                EIAP.remove(g.chkCmps[r]);
            }
        }
    },
    remove: function () {
        var g = this;
        EIAP.form.ComboBox.superclass.remove.call(g);
        if (g.tbarCmp) {
            EIAP.remove(g.tbarCmp);
        }
        g.removeChkCmps();
    }
});﻿EIAP.ComboTree = function () {
    return new EIAP.form.ComboTree(arguments[0]);
};
EIAP.form.ComboTree = EIAP.extend(EIAP.form.TriggerField, {
    async: true,
    store: null,
    searchText: null,
    showSearch: true,
    showMultiTip: false,
    multiSelect: false,
    listHeight: 200,
    listWidth: 260,
    beforeLoad: null,
    afterLoad: null,
    onlyLeafCheck: false,
    cascadeCheck: false,
    initComponent: function () {
        EIAP.form.ComboTree.superclass.initComponent.call(this);
        if (this.beforeLoad) {
            this.on('beforeLoad', this.beforeLoad);
        }
        if (this.afterLoad) {
            this.on('afterLoad', this.afterLoad);
        }
        if (this.readonly) {
            this.async = true;
        }
        if (this.store)
            this.initStore();
    },
    __getType: function () {
        return 'ComboTree';
    },

    __idPrev: function () {
        return 'ComboTree';
    },

    _extMethods: function () {
        return EIAP.form.ComboTree;
    },

    initList: function () {
        var g = this;
        var timestamp = new Date().getTime();
        g.timeStamp = timestamp;
        var list = $('<div></div>');
        list.attr("eiapuiid", g.id).addClass(g.listCss);
        g.list = list;
        g.addLoadMask();
        $("body").append(list);
        g.setListPos();
        g.showShadow();
        g.loading = true;
        if (!g.data) {
            g.fireEvent('beforeLoad', g.store);
            if (g.store) {
                g.store.load({
                    success: function (response) {
                        if (g.timeStamp == timestamp) {
                            g.data = response.data;
                            g.fireEvent('afterLoad', response.data);
                            g.showComboList();
                        }
                    }
                });
            } else {
                throw new Error(EIAP.error.dataError);
            }
        } else {
            g.showComboList();
        }
    },
    showComboList: function () {
        var g = this;
        g.removeLoadMask();
        var id = EIAP.getId("TreePanel");
        g.list.multiBox = $("<div ></div>").addClass(g.multiBoxCls);
        g.multiSelect && g.list.append(g.list.multiBox);
        g.list.append($("<div id='" + id + "'></div>"));
        g.list.bind("click", function (e) {
            e.stopPropagation();
        });
        var selectFn = function () {
            var value = arguments[0].data;
            var flag = true;
            if (g.multiSelect) {
                value = g.tree.tree.getChecked();
                if (value.length < 1) {
                    flag = false;
                }
            } else if (!value) {
                flag = false;
            }
            if (flag) {
                if (g.beforeSelect) {
                    var before = {};
                    before.oldText = g.getValue();
                    before.oldValue = g.getSubmitValue();
                    before.data = value;
                    before.isMulti = g.multiSelect;
                    if (g.beforeSelect(before) == false) {
                        g.hideList();
                        return;
                    }
                }
                g.selectData(value);
                if (g.afterSelect) {
                    var after = {};
                    after.text = g.getValue();
                    after.value = g.getSubmitValue();
                    after.data = value;
                    g.afterSelect(after);
                }
                g.showClear();
            }
            g.hideList();
        };
        var treeCfg = {
            renderTo: id,
            height: g.listHeight,
            data: g.data,
            checkbox: g.multiSelect,
            onlyLeafCheck: g.onlyLeafCheck,
            cascadeCheck: g.cascadeCheck
        };
        if (g.showSearch) {
            var w = g.listWidth - 140;
            w = w < 120 ? 120 : w;
            if (!g.multiSelect) {
                w = g.listWidth - 18;
            }
            var searchbox = {
                xtype: 'SearchBox',
                name: 'searchcmp' + g.id,
                width: w,
                onSearch: function (v) {
                    g.tree.tree.filter(v);
                }
            };
            if (g.searchText) {
                searchbox.displayText = g.searchText;
            }
            treeCfg.tbar = [searchbox];
        }
        if (!g.multiSelect) {
            treeCfg.onClick = selectFn;
        } else {
            treeCfg.onClick = function (node) {
                var treeitembody = $(">div:first", $(node.target));
                if ($(".ux-checkbox", treeitembody).hasClass("ux-checkbox-unchecked")) {
                    $(".ux-checkbox", treeitembody).removeClass("ux-checkbox-unchecked").addClass("ux-checkbox-checked");
                } else {
                    $(".ux-checkbox", treeitembody).removeClass("ux-checkbox-checked").addClass("ux-checkbox-unchecked");
                }
            };
            g.chkCmpId = EIAP.getId("CheckBox");
            var appchk = {
                xtype: "CheckBox",
                id: g.chkCmpId,
                labelWidth: 30,
                labelFirst: false,
                title: g.tAppend
            };
            var btn = {
                title: EIAP.cmpText.ok,
                handler: selectFn,
                iconCls: 'icon-ok'
            };
            if (treeCfg.tbar) {
                treeCfg.tbar.push("->");
                treeCfg.tbar.push(appchk);
                treeCfg.tbar.push(btn);
            } else {
                treeCfg.tbar = ["->", appchk, btn];
            }
        }
        var tree = EIAP.TreePanel(treeCfg);
        tree.parentCmp = this.id;
        g.tree = tree;
        g.dom.triggerbtn.addClass(g.triggerClickCss);
        g.loading = false;
        g.setListPos();
        g.showShadow();
    },
    setListPos: function () {
        var g = this;
        var iptpos = g.dom.field.offset();
        var ipth = g.dom.field.outerHeight(), iptw = g.dom.field.outerWidth();
        var top = iptpos.top + ipth, left = iptpos.left;
        var listh = g.list.height(), listtw = g.list.width();
        if ($(window).height() <= (listh + top)) {
            var tmp = (iptpos.top - ipth - listh + 20);
            if (tmp > 0) {
                top = tmp;
            }
        }
        if ($(window).width() <= (listtw + left)) {
            var tmpleft = (left + iptw + 15 - listtw);
            if (!g.clear) {
                tmpleft += 17;
            }
            if (tmpleft > 0) {
                left = tmpleft;
            }
        }
        var tw = 0;
        $('img', g.dom).each(function () {
            if ($(this).is(":visible"))
                tw += 17;
        });
        var width = g.dom.field.width() + tw + 6;
        width = width < g.listWidth ? g.listWidth : width;
        g.list.css({
            "left": left,
            "top": top,
            "width": width
        }).show();
        g.shadow && g.dom.shadow && g.dom.shadow.updateShadow(g.list);
    },
    initStore: function () {
        var g = this;
        g.store.autoLoad = !g.async;
        g.store.success = function (response) {
            g.data = response.data;
            g.fireEvent('afterLoad', response.data);
        };
        if (!g.async) {
            g.fireEvent('beforeLoad', g.store);
        }
        g.store.params = EIAP.apply(g.store.params || {}, g.getCascadeParams());
        var store = EIAP.Store(g.store);
        g.store = store;
    },
    selectData: function () {
        var g = this;
        var name = g.sysReader.name, data = arguments[0], value, i, chkCmp = null;
        if (g.chkCmpId) {
            chkCmp = EIAP.getCmp(g.chkCmpId);
        }
        if (!g.multiSelect) {
            g.setValue(data[name]);
        } else {
            value = [];
            for (i = 0; i < data.length; i++) {
                value.push(data[i].data[name]);
            }
            if (chkCmp && chkCmp.getValue() === true) {
                var curd = g.getValue();
                for (var a = 0; a < value.length; a++) {
                    $.inArray(value[a], curd) < 0 && curd.push(value[a]);
                }
                value = curd;
            }
            g.setValue(value.toString());
        }
        if (g.field) {
            var rfield = g.sysReader.field, rname;
            value = {};
            if (!data.length) {
                for (i = 0; i < g.field.length; i++) {
                    rname = rfield[i];
                    name = g.field[i];
                    if (data[rname] != undefined && data[rname] != null) {
                        value[name] = data[rname];
                    } else {
                        value[name] = "";
                    }
                }
            } else {
                for (i = 0; i < data.length; i++) {
                    for (var j = 0; j < g.field.length; j++) {
                        rname = rfield[j];
                        name = g.field[j];
                        if (i == 0) {
                            value[name] = [];
                        }
                        value[name].push(data[i].data[rname].toString() ? data[i].data[rname] : "");
                    }
                }
                if (chkCmp && chkCmp.getValue() === true) {
                    var sv = g.submitValue;
                    for (var fn = 0; fn < g.field.length; fn++) {
                        name = g.field[fn];
                        for (var cv = 0; cv < value[name].length; cv++) {
                            if (typeof sv[name] == "string") {
                                sv[name] = [];
                            }
                            $.inArray(value[name][cv], sv[name]) < 0 && sv[name].push(value[name][cv]);
                        }
                    }
                    value = sv;
                }
            }
            g.submitValue = value;
        }
        g.sysValidater();
    },
    getValue: function () {
        var value = EIAP.form.ComboTree.superclass.getValue.call(this);
        if (this.multiSelect) {
            if (!value) {
                value = [];
            } else {
                value = value.split(",");
            }
        }
        return value;
    },

    addEvents: function () {
        var g = this;
        EIAP.form.ComboTree.superclass.addEvents.call(this);
        g.canClear && g.dom.clearTrigger.bind("click", function () {
            g.tree && g.tree.tree.cancelSelect();
        });
    },
    remove: function () {
        var g = this;
        EIAP.form.ComboTree.superclass.remove.call(this);
        EIAP.remove(g.tree);
        g.tree = null;
    }
});﻿EIAP.SearchBox = function () {
    return new EIAP.form.SearchBox(arguments[0]);
};
EIAP.form.SearchBox = EIAP.extend(EIAP.form.TriggerField, {
    editable: true,
    onSearch: null,
    width: 260,
    triggerCss: "ux-search-trigger",
    initComponent: function () {
        EIAP.form.SearchBox.superclass.initComponent.call(this);
    },
    __getType: function () {
        return 'SearchBox';
    },

    __idPrev: function () {
        return 'SearchBox';
    },

    _extMethods: function () {
        return EIAP.form.SearchBox;
    },
    afterClear: function () {
        this.doSearch();
    },
    doSearch: function () {
        var g = this;
        var v = g.getValue();
        if (v == "") {
            g.hideClear();
        } else {
            g.showClear();
        }
        g.onSearch.call(g, v);
    },
    onClick: function () {
    },
    addEvents: function () {
        var g = this;
        if (!g.readonly && g.onSearch instanceof Function && !g.dom.triggerbtn.hasClass(g.triggerDisableCss)) {
            g.dom.triggerbtn.bind("click", function () {
                g.doSearch();
            });
            g.dom.field.bind("keyup", function (e) {
                if (e.keyCode == 13) {
                    g.doSearch();
                }
            });
        }
        EIAP.form.SearchBox.superclass.addEvents.call(this);
    }
});﻿EIAP.ComboGrid = function () {
    return new EIAP.form.ComboGrid(arguments[0]);
};
EIAP.form.ComboGrid = EIAP.extend(EIAP.form.TriggerField, {
    async: false,
    searchText: null,
    searchParams: null,
    listWidth: 400,
    listHeight: 200,
    showSearch: true,
    beforeLoad: null,
    afterLoad: null,
    gridCfg: {},
    initComponent: function () {
        EIAP.form.ComboGrid.superclass.initComponent.call(this);
    },
    __getType: function () {
        return 'ComboGrid';
    },

    __idPrev: function () {
        return 'ComboGrid';
    },

    _extMethods: function () {
        return EIAP.form.ComboGrid;
    },
    initList: function () {
        var g = this;
        if (!g.list) {
            var id = EIAP.getId("GridPanel");
            var list = $("<div class='" + g.listCss + "'><div id='" + id + "'></div></div>");
            list.bind("click", function (e) {
                e.stopPropagation();
            });
            g.list = list;
            $("body").append(list);
            g.setListPos();
            var selectFn = function () {
                var value = g.grid.getSelectRow();
                if (value && ((value instanceof Array) && value.length > 0 || !(value instanceof Array))) {
                    if (g.beforeSelect) {
                        var before = {};
                        before.oldText = g.getValue();
                        before.oldValue = g.getSubmitValue();
                        before.data = value;
                        before.isMulti = g.gridCfg.multiselect;
                        if (g.beforeSelect(before) == false) {
                            g.hideList();
                            return;
                        }
                    }
                    g.selectData(value);
                    if (g.afterSelect) {
                        var after = {};
                        after.text = g.getValue();
                        after.value = g.getSubmitValue();
                        after.data = value;
                        g.afterSelect(after);
                    }
                    g.showClear();
                }
                g.hideList();
            };
            g.gridCfg.recordtext = EIAP.cmpText.recordtext;
            g.gridCfg.pager = null;
            g.gridCfg.postData = EIAP.apply(g.gridCfg.postData || {}, g.getCascadeParams());
            var cfg = {
                renderTo: id,
                height: g.listHeight,
                searchText: g.searchText,
                showSearch: g.showSearch,
                searchParams: g.searchParams,
                gridCfg: g.gridCfg
            };
            if (!g.gridCfg.multiselect) {
                g.gridCfg.ondblClickRow = selectFn;
            } else {
                g.chkCmpId = EIAP.getId("CheckBox");
                var appchk = {
                    xtype: "CheckBox",
                    id: g.chkCmpId,
                    labelWidth: 30,
                    labelFirst: false,
                    title: g.tAppend
                };
                cfg.tbar = [
                    appchk, { title: EIAP.cmpText.ok, handler: selectFn, iconCls: 'icon-ok' }
                ];
            }
            var grid = EIAP.GridPanel(cfg);
            grid.parentCmp = this.id;
            g.grid = grid;
            g.dom.triggerbtn.addClass(g.triggerClickCss);
            g.loading = false;
            g.setListPos();
            g.showShadow();
        }
    },
    setListPos: function () {
        var g = this;
        var iptpos = g.dom.field.offset();
        var ipth = g.dom.field.outerHeight(), iptw = g.dom.field.outerWidth();
        var top = iptpos.top + ipth, left = iptpos.left;
        var listh = g.list.height(), listtw = g.list.width();
        if ($(window).height() <= (listh + top)) {
            var tmptop = (iptpos.top - ipth - listh + 20);
            if (tmptop > 0) {
                top = tmptop;
            }
        }
        if ($(window).width() <= (listtw + left)) {
            var tmpleft = (left + iptw + 15 - listtw);
            if (g.canClear && !g.clear) {
                tmpleft += 17;
            }
            if (tmpleft > 0) {
                left = tmpleft;
            }
        }
        var tw = 0;
        $('img', g.dom).each(function () {
            if ($(this).is(":visible"))
                tw += 17;
        });
        var width = g.dom.field.width() + tw + 6;
        width = width < g.listWidth ? g.listWidth : width;
        g.list.css({
            "left": left,
            "top": top,
            width: width
        }).show();
        g.shadow && g.dom.shadow && g.dom.shadow.updateShadow(g.list);
    },

    selectData: function () {
        var g = this;
        var name = g.sysReader.name, data = arguments[0], value, i, chkCmp = null;
        if (g.chkCmpId) {
            chkCmp = EIAP.getCmp(g.chkCmpId);
        }
        if (!g.gridCfg.multiselect) {
            g.setValue(data[name]);
        } else {
            value = [];
            for (i = 0; i < data.length; i++) {
                value.push(data[i][name]);
            }
            if (chkCmp && chkCmp.getValue() === true) {
                var curd = g.getValue();
                for (var a = 0; a < value.length; a++) {
                    $.inArray(value[a], curd) < 0 && curd.push(value[a]);
                }
                value = curd;
            }
            g.setValue(value.toString());
        }

        if (g.field) {
            var rfield = g.sysReader.field, rname;
            value = {};
            if (!data.length) {
                for (i = 0; i < g.field.length; i++) {
                    rname = rfield[i];
                    name = g.field[i];
                    if (data[rname] != undefined && data[rname] != null) {
                        value[name] = data[rname];
                    } else {
                        value[name] = "";
                    }
                }
            } else {
                for (i = 0; i < data.length; i++) {
                    for (var j = 0; j < g.field.length; j++) {
                        rname = rfield[j];
                        name = g.field[j];
                        if (i == 0) {
                            value[name] = [];
                        }
                        value[name].push(data[i][rname].toString() ? data[i][rname] : "");
                    }
                }
                if (chkCmp && chkCmp.getValue() === true) {
                    var sv = g.submitValue;
                    for (var fn = 0; fn < g.field.length; fn++) {
                        name = g.field[fn];
                        for (var cv = 0; cv < value[name].length; cv++) {
                            if (typeof sv[name] == "string") {
                                sv[name] = [];
                            }
                            $.inArray(value[name][cv], sv[name]) < 0 && sv[name].push(value[name][cv]);
                        }
                    }
                    value = sv;
                }
            }
            g.submitValue = value;
        }
        g.sysValidater();
    },

    getValue: function () {
        var value = EIAP.form.ComboGrid.superclass.getValue.call(this);
        if (this.gridCfg.multiselect) {
            if (!value) {
                value = [];
            } else {
                value = value.split(",");
            }
        }
        return value;
    },
    remove: function () {
        var g = this;
        EIAP.form.ComboGrid.superclass.remove.call(this);
        EIAP.remove(g.grid);
        g.grid = null;
    },

    updatePostParam: function () {
        if (this.grid) {
            this.grid.resetParam();
            this.grid.setPostParams(this.getCascadeParams());
        }
    }
});﻿EIAP.FieldGroup = function () {
    return new EIAP.form.FieldGroup(arguments[0]);
};

EIAP.form.FieldGroup = EIAP.extend(EIAP.form.TextField, {
    width: 400,
    isFormField: false,
    needValid: true,
    spaceCss: "ux-fieldgroup-space",
    itemCss: "ux-fieldgroup-item",
    initComponent: function () {
        EIAP.form.FieldGroup.superclass.initComponent.call(this);
        if (this.readonly) {
            var ds = this.defaultStyle || {};
            this.defaultStyle = EIAP.apply(ds, { readonly: true });
        }
    },
    __getType: function () {
        return 'FieldGroup';
    },

    __idPrev: function () {
        return 'FieldGroup';
    },

    _extMethods: function () {
        return EIAP.form.FieldGroup;
    },

    _render: function () {
        var g = this;
        g.dom = g.renderTo ? $(g.element) : $("<div></div>");
        g.dom.addClass(g.domCss);
        g.initLabel();
        g.setWidth(g.width);
    },
    sysValidater: function () {
        var g = this;
        if (g.hidden)
            return true;
        if (g.needValid && !g.allowBlank)
            return g.doValidate(g.items);
        return true;
    },
    doValidate: function () {
        var items = arguments[0];
        var flag = true;
        if (items) {
            for (var i = 0; i < items.length; i++) {
                var item = EIAP.getCmp(items[i]);
                if (item.isDefined) {
                    if (item.isFormField) {
                        var tmp = item.sysValidater();
                        flag = flag && tmp;
                    } else {
                        flag = this.doValidate(item.items) && flag;
                    }
                }
            }
        }
        return flag;
    },
    setAllowBlank: function (v) {
        var g = this;
        EIAP.form.FieldGroup.superclass.setAllowBlank.call(this);
        if (g.items) {
            for (var i = 0; i < g.items.length; i++) {
                var item = EIAP.getCmp(g.items[i]);
                item.setAllowBlank(v);
            }
        }
    },
    setWidth: function () {
        var width = parseInt(arguments[0]);
        if (width) {
            if (typeof arguments[0] == "string" && arguments[0].indexOf("%") > -1) {
                width /= 100;
                width *= this.dom.parent().width();
                if (this.dom.label) {
                    if (!this.labelWidth) {
                        if (width * 7 / 23 < 40) {
                            this.setLabelWidth(40);
                            width -= 40;
                        }
                        if (width * 7 / 23 > 70) {
                            this.setLabelWidth(70);
                            width -= 70;
                        } else {
                            this.setLabelWidth(width * 7 / 23);
                            width -= (width * 7 / 23);
                        }
                    } else {
                        this.setLabelWidth(this.labelWidth);
                        width -= this.labelWidth;
                    }
                }
                width -= 10;
            }
            this.dom.width(width);
            this.width = arguments[0];
        }
    },
    addItems: function () {
        var g = this, items = g.options.items;
        for (var i = 0; i < items.length; i++) {
            var item = items[i];
            item.allowBlank = g.allowBlank;
            if (typeof item == "string") {
                var span = $("<span>" + item + "</span>").addClass(g.spaceCss).addClass(g.itemCss);
                g.dom.append(span);
            } else {
                var xtype = item.xtype ? item.xtype : g.defaultType;
                EIAP.applyIf(item, g.defaultStyle);
                if (!xtype) {
                    throw new Error(EIAP.error.noXtype);
                }
                var cmp = eval("EIAP." + xtype);
                if (!cmp) {
                    throw new Error(String.format(EIAP.error.noCmp, xtype));
                }
                cmp = cmp.call(cmp, item);
                cmp.dom.addClass(g.itemCss);
                g.dom.append(cmp.dom);
                g.items.push(cmp.id);
            }
        }
    },
    reset: function () {
        for (var i = 0; i < this.items.length; i++) {
            var tmpcmp = EIAP.getCmp(this.items[i]);
            if (tmpcmp instanceof EIAP.form.Field) {
                tmpcmp.reset();
            }
        }
    }
});﻿EIAP.MonthField = function () {
    return new EIAP.form.MonthField(arguments[0]);
};
EIAP.form.MonthField = EIAP.extend(EIAP.form.TriggerField, {
    format: "Y-m",
    triggerCss: "ux-date-trigger",
    listInner: "ux-month-body",
    listItemCss: "ux-month-item",
    seletedCss: "itemselect",
    yearsBoxCss: "ux-month-years",
    monthsBoxCss: "ux-month-months",
    yearnavCss: "ux-month-yearnav",
    btnprevCss: "ux-month-yearnav-prev",
    btnnextCss: "ux-month-yearnav-next",
    monthBtnboxCss: "ux-month-btnsbox",
    monthBtnCss: "ux-monthbtn",
    btnyear: "button-year",
    onlyYear: "year",
    yearsp: 10,
    initComponent: function () {
        this.date = "";
        EIAP.form.MonthField.superclass.initComponent.call(this);
        this.initMonth();
    },
    __getType: function () {
        return 'MonthField';
    },

    __idPrev: function () {
        return 'MonthField';
    },

    _extMethods: function () {
        return EIAP.form.MonthField;
    },
    showList: function () {
        var g = this;
        if (!g.loading && g.list) {
            g.list.show();
            g.dom.triggerbtn.addClass(g.triggerClickCss);
            g.setListPos();
            g.showShadow();
        } else {
            g.initList();
        }
    },
    initList: function () {
        var g = this;
        var list = $('<div></div>');
        list.attr("eiapuiid", g.id).addClass(g.listCss);
        g.list = list;
        var listbox = $('<div eiapuiid="' + g.id + '" class="' + g.listInner + '"></div>');
        g.yearbox = $('<div></div>').addClass(g.yearsBoxCss);
        g.yearnav = $('<div></div>').addClass(g.yearnavCss);
        g.yearprev = $('<button></button>').addClass(g.btnprevCss);
        g.yearnext = $('<button></button>').addClass(g.btnnextCss);
        g.yearnav.append(g.yearprev).append(g.yearnext);
        g.yearbox.append(g.yearnav);
        if (g.format.indexOf("m") > 0) {
            g.monthbox = $('<div></div>').addClass(g.monthsBoxCss);
            listbox.append(g.yearbox).append(g.monthbox);
        } else {
            g.yearprev.addClass(g.btnyear);
            g.yearnext.addClass(g.btnyear);
            g.yearbox.addClass(g.onlyYear);
            listbox.append(g.yearbox);
            g.yearsp = 20;
        }
        var listbtnbox = $('<div></div>').addClass(g.monthBtnboxCss);
        g.listbtnOk = $("<div class='" + g.monthBtnCss + " btnok'>" + EIAP.cmpText.ok + "</div>");
        g.listbtnCancel = $("<div class='" + g.monthBtnCss + " btncancel'>" + EIAP.cmpText.cancel + "</div>");
        listbtnbox.append(g.listbtnOk).append(g.listbtnCancel);
        g.list.append(listbox).append(listbtnbox);
        g.dom.triggerbtn.addClass(g.triggerClickCss);
        g.initMonthPicker();
        $("body").append(list);
        g.addListItemEvent();
        g.setListPos();
        g.showShadow();
        g.loading = false;
    },
    initMonthPicker: function () {
        var g = this;
        g.monthbox && g.setMonths();
        g.initYearItem();
        g.setYears();
    },
    initMonth: function () {
        var d = this.activeDate || this.value;
        this.curYear = (new Date()).getFullYear();
        if (d) {
            this.mpSelMonth = d.substr(4, 2);
            this.mpSelYear = Number(d.substr(0, 4));
        } else {
            var m = (new Date()).getMonth() + 1;
            this.mpSelMonth = Number(m) < 10 ? "0" + m : m;
            this.mpSelYear = this.curYear;
        }
    },
    setMonths: function () {
        var g = this;
        if (EIAP.calendar.Calendar) {
            var months = EIAP.calendar.Calendar.month;
            for (var i = 0; i < months.length; i++) {
                var itemdom = $("<div></div>").addClass(g.listItemCss);
                if ((i + 1) < 10) {
                    itemdom.data("itemdata", "0" + (i + 1));
                } else {
                    itemdom.data("itemdata", (i + 1));
                }
                var item = $("<a href='#' hidefocus='on'></a>").html(months[i]);
                if (Number(g.mpSelMonth) == (i + 1)) {
                    item.addClass(g.seletedCss);
                }
                itemdom.append(item);
                g.monthbox.append(itemdom);
            }
        } else {
            throw new Error(String.format(EIAP.error.noCmp, "EIAP.Calendar"));
        }
    },
    initYearItem: function () {
        var g = this;
        for (var i = 0; i < g.yearsp; i++) {
            var itemdom = $("<div></div>").addClass(g.listItemCss);
            var item = $("<a href='#' hidefocus='on'></a>");
            itemdom.append(item);
            g.yearbox.append(itemdom);
        }
    },
    setYears: function (y) {
        var g = this;
        g.mpyear = y || g.mpSelYear;
        var ys = g.yearbox.find("div." + g.listItemCss), tmpyear = g.mpyear - 10;
        for (var i = 1; i <= g.yearsp; i++) {
            var it = $(ys[i - 1]), y2;
            y2 = tmpyear + i;
            if (g.curYear == y2) {
                it.find("a").addClass(g.seletedCss);
            } else {
                it.find("a").removeClass(g.seletedCss);
            }
            it.data("itemdata", y2).find("a").html(y2);
        }
    },
    setListPos: function () {
        var g = this;
        var iptpos = g.dom.field.offset();
        var ipth = g.dom.field.outerHeight();
        var top = iptpos.top + ipth - 1;
        var listh = g.list.height();
        if ($(window).height() <= (listh + top)) {
            var tmp = (iptpos.top - ipth - listh + 20);
            if (tmp > 0) {
                top = tmp;
            }
        }
        var tw = 0;
        $('img', g.dom).each(function () {
            if ($(this).is(":visible"))
                tw += 17;
        });
        g.list.css({
            "left": iptpos.left,
            "top": top,
            "width": 176
        }).show();
        g.shadow && g.dom.shadow && g.dom.shadow.updateShadow(g.list);
    },
    addListItemEvent: function () {
        var g = this;
        g.list.bind("click", function () {
            return false;
        });
        g.yearprev.bind("click", function () {
            g.setYears(g.mpyear - g.yearsp);
        });
        g.yearnext.bind("click", function () {
            g.setYears(g.mpyear + g.yearsp);
        });
        g.listbtnOk.bind("click", function () {
            var value = g.getSelectValue();
            if (g.beforeSelect) {
                var before = {};
                before.oldText = g.getValue();
                before.oldValue = g.getSubmitValue();
                before.data = value;
                if (g.beforeSelect(before) == false) {
                    g.hideList();
                    return;
                }
            }
            g.setValue(value);
            g.sysValidater();
            g.showClear();
            g.hideList();
            if (g.afterSelect) {
                var after = {};
                after.text = g.getValue();
                after.value = g.getSubmitValue();
                after.data = value;
                g.afterSelect(after);
            }
        });
        g.listbtnCancel.bind("click", function () {
            g.hideList();
        });
        $("." + g.listItemCss, g.yearbox).each(function () {
            var item = $(this);
            item.bind("click", function () {
                g.mpSelYear = Number(item.data("itemdata"));
                item.parent().find("a").removeClass(g.seletedCss);
                item.find("a").addClass(g.seletedCss);
                if (g.monthbox) {
                    return false;
                } else {
                    g.listbtnOk.click();
                }
            });
        });
        if (g.monthbox) {
            $("." + g.listItemCss, g.monthbox).each(function () {
                var item = $(this);
                item.bind("click", function () {
                    g.mpSelMonth = item.data("itemdata");
                    item.parent().find("a").removeClass(g.seletedCss);
                    item.find("a").addClass(g.seletedCss);
                    g.listbtnOk.click();
                });
            });
        }
    },
    reset: function () {
        EIAP.form.MonthField.superclass.reset.call(this);
        this.date = "";
    },
    getSelectValue: function () {
        var g = this;
        var m = g.monthbox ? g.mpSelMonth.toString() : "", y = g.mpSelYear.toString();
        return y + m;
    },
    getValue: function () {
        return this.date;
    },
    setValue: function (value) {
        if (!value || isNaN(value) || (value < 100001 && value > 999912)) {
            return;
        }
        var v = value.toString();
        var y = v.substr(0, 4);
        this.date = v;
        var mStr = this.format.replace("Y", y);
        mStr = mStr.replace("m", v.substr(4, 2));
        this.dom.field.val(mStr);
        EIAP.form.MonthField.superclass.setValue.call(this, mStr);
    }
});﻿EIAP.Calendar = function () {
    return new EIAP.calendar.Calendar(arguments[0]);
};

EIAP.calendar.Calendar = EIAP.extend(EIAP.UIComponent, {
    format: "Y-m-d hh:mm",
    showTime: true,
    domCss: "ux-date",
    width: 200,
    height: 200,
    callback: null,

    initComponent: function () {
        EIAP.calendar.Calendar.superclass.initComponent.call(this);
    },
    __getType: function () {
        return 'Calendar';
    },

    __idPrev: function () {
        return 'Calendar';
    },

    _extMethods: function () {
        return EIAP.calendar.Calendar;
    },

    _render: function () {
        var g = this;
        g.dom = g.renderTo ? $(g.element) : $("<div></div>");
        g.dom.addClass(g.domCss);
        g.setWidth(g.width);
        g.setHeight(g.height);
        g.initHeader();
        g.initBody();
        g.initTbar();
        g.buttons = {
            btnPrevYear: $(".ux-box-dateeditor-header-prevyear", g.header),
            btnNextYear: $(".ux-box-dateeditor-header-nextyear", g.header),
            btnPrevMonth: $(".ux-box-dateeditor-header-prevmonth", g.header),
            btnNextMonth: $(".ux-box-dateeditor-header-nextmonth", g.header),
            btnYear: $(".ux-box-dateeditor-header-year", g.header),
            btnMonth: $(".ux-box-dateeditor-header-month", g.header)
        };
        var nowDate = new Date();
        g.now = {
            year: nowDate.getFullYear(),
            month: nowDate.getMonth() + 1, // 注意这里
            day: nowDate.getDay(),
            date: nowDate.getDate(),
            hour: nowDate.getHours(),
            minute: nowDate.getMinutes()
        };
        // 当前的时间
        g.currentDate = {
            year: nowDate.getFullYear(),
            month: nowDate.getMonth() + 1,
            day: nowDate.getDay(),
            date: nowDate.getDate(),
            hour: nowDate.getHours(),
            minute: nowDate.getMinutes()
        };
        // 选择的时间
        g.selectedDate = null;
        // 使用的时间
        g.usedDate = null;
        g.initDate();
        // 设置主体
        g.bulidContent();
        g.addEvents();
        g.set(g);
    },

    setWidth: function () {
        var width = parseInt(arguments[0]);
        if (width)
            this.dom.width(width);
    },
    setHeight: function () {
        var height = parseInt(arguments[0]);
        if (height) {
            this.dom.height(height);
        }
    },

    initHeader: function () {
        var g = this;
        var header = "";
        header += "<div class='ux-box-dateeditor-header'>";
        header += "<div class='ux-box-dateeditor-header-btn ux-box-dateeditor-header-prevyear'><span></span></div>";
        header += "<div class='ux-box-dateeditor-header-btn ux-box-dateeditor-header-prevmonth'><span></span></div>";
        header += "<div class='ux-box-dateeditor-header-text'><a class='ux-box-dateeditor-header-month'></a>  <a  class='ux-box-dateeditor-header-year'></a></div>";
        header += "<div class='ux-box-dateeditor-header-btn ux-box-dateeditor-header-nextmonth'><span></span></div>";
        header += "<div class='ux-box-dateeditor-header-btn ux-box-dateeditor-header-nextyear'><span></span></div>";
        header += "</div>";
        g.header = $(header);
        g.dom.append(g.header);

    },

    initBody: function () {
        var g = this;
        var body = "";
        body += "<div class='ux-box-dateeditor-body'>";
        body += "<table cellpadding='0' cellspacing='0' border='0' class='ux-box-dateeditor-calendar'>";
        body += "<thead>";
        body += "<tr><td align='center'></td><td align='center'></td><td align='center'></td><td align='center'></td><td align='center'></td><td align='center'></td><td align='center'></td></tr>";
        body += "</thead>";
        body += "<tbody>";
        body += "<tr class='ux-first'><td align='center'></td><td align='center'></td><td align='center'></td><td align='center'></td><td align='center'></td><td align='center'></td><td align='center'></td></tr><tr><td align='center'></td><td align='center'></td><td align='center'></td><td align='center'></td><td align='center'></td><td align='center'></td><td align='center'></td></tr><tr><td align='center'></td><td align='center'></td><td align='center'></td><td align='center'></td><td align='center'></td><td align='center'></td><td align='center'></td></tr><tr><td align='center'></td><td align='center'></td><td align='center'></td><td align='center'></td><td align='center'></td><td align='center'></td><td align='center'></td></tr><tr><td align='center'></td><td align='center'></td><td align='center'></td><td align='center'></td><td align='center'></td><td align='center'></td><td align='center'></td></tr><tr><td align='center'></td><td align='center'></td><td align='center'></td><td align='center'></td><td align='center'></td><td align='center'></td><td align='center'></td></tr>";
        body += "</tbody>";
        body += "</table>";
        body += "<ul class='ux-box-dateeditor-monthselector'><li></li><li></li><li></li><li></li><li></li><li></li><li></li><li></li><li></li><li></li><li></li><li></li></ul>";
        body += "<ul class='ux-box-dateeditor-yearselector'><li></li><li></li><li></li><li></li><li></li><li></li><li></li><li></li><li></li><li></li><li></li><li></li></ul>";
        body += "<ul class='ux-box-dateeditor-hourselector'><li></li><li></li><li></li><li></li><li></li><li></li><li></li><li></li><li></li><li></li><li></li><li></li><li></li><li></li><li></li><li></li><li></li><li></li><li></li><li></li><li></li><li></li><li></li><li></li></ul>";
        body += "<ul class='ux-box-dateeditor-minuteselector'><li></li><li></li><li></li><li></li><li></li><li></li><li></li><li></li><li></li><li></li><li></li><li></li><li></li><li></li><li></li><li></li><li></li><li></li><li></li><li></li><li></li><li></li><li></li><li></li><li></li><li></li><li></li><li></li><li></li><li></li><li></li><li></li><li></li><li></li><li></li><li></li><li></li><li></li><li></li><li></li><li></li><li></li><li></li><li></li><li></li><li></li><li></li><li></li><li></li><li></li><li></li><li></li><li></li><li></li><li></li><li></li><li></li><li></li><li></li><li></li></ul>";
        body += "</div>";
        g.body = $(body);
        g.dom.append(g.body);
        g.body.thead = $("thead", g.body);
        g.body.tbody = $("tbody", g.body);
        g.body.monthselector = $(".ux-box-dateeditor-monthselector", g.body);
        g.body.yearselector = $(".ux-box-dateeditor-yearselector", g.body);
        g.body.hourselector = $(".ux-box-dateeditor-hourselector", g.body);
        g.body.minuteselector = $(".ux-box-dateeditor-minuteselector", g.body);
    },

    initTbar: function () {
        var g = this, tbar = null;
        if (EIAP.ToolBar && EIAP.Button) {
            tbar = EIAP.ToolBar({
                items: [
                    { title: EIAP.calendar.Calendar.today, handler: function () {
                        g.currentDate = {
                            year: g.now.year,
                            month: g.now.month,
                            day: g.now.day,
                            date: g.now.date
                        };
                        g.selectedDate = {
                            year: g.now.year,
                            month: g.now.month,
                            day: g.now.day,
                            date: g.now.date
                        };
                        g.setDate();
                    }, isFlat: false
                    }
                ]
            });
            g.dom.append(tbar.dom);
            g.items.push(tbar.id);
        }
        g.toolbar = tbar ? tbar.dom : $('<div></div>');
        g.toolbar.addClass("ux-box-dateeditor-toolbar");
        g.showTime && g.toolbar.addClass("ux-box-dateeditor-toolbar-notime");
        var time = $('<div class="ux-box-dateeditor-time"></div>');
        g.toolbar.prepend(time);
        g.toolbar.time = $(".ux-box-dateeditor-time", g.toolbar);
        g.toolbar.time.hour = $("<a></a>");
        g.toolbar.time.minute = $("<a></a>");
    },

    initDate: function () {
        var g = this;
        // 初始化数据
        // 设置周日至周六
        $("td", g.body.thead).each(function (i, td) {
            $(td).html(EIAP.calendar.Calendar.week[i]);
        });
        // 设置一月到十一二月
        $("li", g.body.monthselector).each(function (i, li) {
            $(li).html(EIAP.calendar.Calendar.month[i]);
        });
        // 设置时间
        if (g.showTime) {
            g.toolbar.time.show();
            g.toolbar.time.append(g.toolbar.time.hour).append(":").append(g.toolbar.time.minute);
            $("li", g.body.hourselector).each(function (i) {
                var str = i;
                if (i < 10)
                    str = "0" + i.toString();
                $(this).html(str);
            });
            $("li", g.body.minuteselector).each(function (i) {
                var str = i;
                if (i < 10)
                    str = "0" + i.toString();
                $(this).html(str);
            });
        }
    },

    addEvents: function () {
        var g = this;
        // 日期 点击
        $("td", g.body.tbody).hover(function () {
            if ($(this).hasClass("ux-box-dateeditor-today"))
                return;
            $(this).addClass("ux-box-dateeditor-over");
        }, function () {
            $(this).removeClass("ux-box-dateeditor-over");
        }).click(function () {
            $(".ux-box-dateeditor-selected", g.body.tbody).removeClass("ux-box-dateeditor-selected");
            if (!$(this).hasClass("ux-box-dateeditor-today"))
                $(this).addClass("ux-box-dateeditor-selected");
            g.currentDate.date = parseInt($(this).html());
            g.currentDate.day = new Date(g.currentDate.year,
					g.currentDate.month - 1, 1).getDay();
            if ($(this).hasClass("ux-box-dateeditor-out")) {
                if ($("tr", g.body.tbody).index($(this).parent()) == 0) {
                    if (--g.currentDate.month == 0) {
                        g.currentDate.month = 12;
                        g.currentDate.year--;
                    }
                } else {
                    if (++g.currentDate.month == 13) {
                        g.currentDate.month = 1;
                        g.currentDate.year++;
                    }
                }
            }
            g.selectedDate = {
                year: g.currentDate.year,
                month: g.currentDate.month,
                date: g.currentDate.date
            };
            g.setDate();
        });

        $(".ux-box-dateeditor-header-btn", g.header).hover(function () {
            $(this).addClass("ux-box-dateeditor-header-btn-over");
        }, function () {
            $(this).removeClass("ux-box-dateeditor-header-btn-over");
        });
        // 选择年份
        g.buttons.btnYear.click(function () {
            // build year list
            if (!g.body.yearselector.is(":visible")) {
                $("li", g.body.yearselector).each(function (i) {
                    var currentYear = g.currentDate.year
											+ (i - 4);
                    if (currentYear == g.currentDate.year)
                        $(this).addClass("ux-selected");
                    else
                        $(this).removeClass("ux-selected");
                    $(this).html(currentYear);
                });
            }
            g.body.yearselector.slideToggle();
            return false;
        });

        $("li", g.body.yearselector).click(function () {
            g.currentDate.year = parseInt($(this).html());
            g.body.yearselector.slideToggle();
            g.bulidContent();
            return false;
        });
        // select month
        g.buttons.btnMonth.click(function () {
            $("li", g.body.monthselector).each(function (i) {
                // add selected style
                if (g.currentDate.month == i + 1)
                    $(this).addClass("ux-selected");
                else
                    $(this).removeClass("ux-selected");
            });
            g.body.monthselector.slideToggle();
            return false;
        });

        $("li", g.body.monthselector).click(function () {
            var index = $("li", g.body.monthselector).index(this);
            g.currentDate.month = index + 1;
            g.body.monthselector.slideToggle();
            g.bulidContent();
            return false;
        });

        // 选择小时
        g.toolbar.time.hour.click(function () {
            $("li", g.body.hourselector).each(function (i) {
                // add selected style
                if (g.currentDate.hour == i)
                    $(this).addClass("ux-selected");
                else
                    $(this).removeClass("ux-selected");
            });
            g.body.hourselector.slideToggle();
            return false;
        });
        g.body.hourselector.hover(function () {
        }, function () {
            $(this).slideUp("fast");
        });
        $("li", g.body.hourselector).click(function () {
            var index = $("li", g.body.hourselector).index(this);
            g.currentDate.hour = index;
            g.body.hourselector.slideToggle();
            g.bulidContent();
            return false;
        });
        // 选择分钟
        g.toolbar.time.minute.click(function () {
            $("li", g.body.minuteselector).each(function (i) {
                // add selected style
                if (g.currentDate.minute == i)
                    $(this).addClass("ux-selected");
                else
                    $(this).removeClass("ux-selected");
            });
            g.body.minuteselector.slideToggle("fast", function () {
                var index = $("li", this).index($('li.ux-selected', this));
                if (index > 29) {
                    var offSet = ($('li.ux-selected', this).offset().top - $(this)
							.offset().top);
                    $(this).animate({
                        scrollTop: offSet
                    });
                }
            });
            return false;
        });
        g.body.minuteselector.hover(function () {
        }, function () {
            $(this).slideUp("fast");
        });
        $("li", g.body.minuteselector).click(function () {
            var index = $("li", g.body.minuteselector).index(this);
            g.currentDate.minute = index;
            g.body.minuteselector.slideToggle("fast");
            g.bulidContent();
            return false;
        });

        // 上个月
        g.buttons.btnPrevMonth.click(function () {
            if (--g.currentDate.month == 0) {
                g.currentDate.month = 12;
                g.currentDate.year--;
            }
            g.bulidContent();
            return false;
        });
        // 下个月
        g.buttons.btnNextMonth.click(function () {
            if (++g.currentDate.month == 13) {
                g.currentDate.month = 1;
                g.currentDate.year++;
            }
            g.bulidContent();
            return false;
        });
        // 上一年
        g.buttons.btnPrevYear.click(function () {
            g.currentDate.year--;
            g.bulidContent();
            return false;
        });
        // 下一年
        g.buttons.btnNextYear.click(function () {
            g.currentDate.year++;
            g.bulidContent();
            return false;
        });
    },
    setDate: function () {
        var g = this;
        if (!this.selectedDate) return;
        var month = g.selectedDate.month;
        var day = g.selectedDate.date;
        if (month < 10) {
            month = "0" + month;
        }
        if (day < 10) {
            day = "0" + day;
        }
        this.currentDate.hour = parseInt(g.toolbar.time.hour.html(), 10);
        if (this.currentDate.hour < 10) {
            this.currentDate.hour = "0" + this.currentDate.hour;
        }
        this.currentDate.minute = parseInt(g.toolbar.time.minute.html(), 10);
        if (this.currentDate.minute < 10) {
            this.currentDate.minute = "0" + this.currentDate.minute;
        }
        var date = g.format;
        date = date.replace(/Y/g, g.selectedDate.year);
        date = date.replace(/mm/g, g.currentDate.minute);
        date = date.replace(/hh/g, g.currentDate.hour);
        date = date.replace(/m/g, month);
        date = date.replace(/d/g, day);
        if (g.callback) {
            g.callback.call(this, date);
        }
    },
    bulidContent: function () {
        var g = this;
        // 当前月第一天星期
        var thismonthFirstDay = new Date(g.currentDate.year,
				g.currentDate.month - 1, 1).getDay();
        // 当前月天数
        var nextMonth = g.currentDate.month;
        var nextYear = g.currentDate.year;
        if (++nextMonth == 13) {
            nextMonth = 1;
            nextYear++;
        }
        var monthDayNum = new Date(nextYear, nextMonth - 1, 0).getDate();
        // 当前上个月天数
        var prevMonthDayNum = new Date(g.currentDate.year, g.currentDate.month
						- 1, 0).getDate();

        g.buttons.btnMonth.html(EIAP.calendar.Calendar.month[g.currentDate.month - 1]);
        g.buttons.btnYear.html(g.currentDate.year);
        g.toolbar.time.hour.html(g.currentDate.hour);
        g.toolbar.time.minute.html(g.currentDate.minute);
        if (g.toolbar.time.hour.html().length == 1)
            g.toolbar.time.hour.html("0" + g.toolbar.time.hour.html());
        if (g.toolbar.time.minute.html().length == 1)
            g.toolbar.time.minute.html("0" + g.toolbar.time.minute.html());
        $("td", this.body.tbody).each(function () {
            this.className = "";
        });
        $("tr", this.body.tbody).each(function (i, tr) {
            $("td", tr).each(function (j, td) {
                var id = i * 7 + (j - thismonthFirstDay);
                var showDay = id + 1;
                if (g.selectedDate && g.currentDate.year == g.selectedDate.year
						&& g.currentDate.month == g.selectedDate.month
						&& id + 1 == g.selectedDate.date) {
                    if (j == 0 || j == 6) {
                        $(td).addClass("ux-box-dateeditor-holiday");
                    }
                    $(td).addClass("ux-box-dateeditor-selected");
                    $(td).siblings().removeClass("ux-box-dateeditor-selected");
                } else if (g.currentDate.year == g.now.year
						&& g.currentDate.month == g.now.month
						&& id + 1 == g.now.date) {
                    if (j == 0 || j == 6) {
                        $(td).addClass("ux-box-dateeditor-holiday");
                    }
                    $(td).addClass("ux-box-dateeditor-today");
                } else if (id < 0) {
                    showDay = prevMonthDayNum + showDay;
                    $(td).addClass("ux-box-dateeditor-out")
							.removeClass("ux-box-dateeditor-selected");
                } else if (id > monthDayNum - 1) {
                    showDay = showDay - monthDayNum;
                    $(td).addClass("ux-box-dateeditor-out")
							.removeClass("ux-box-dateeditor-selected");
                } else if (j == 0 || j == 6) {
                    $(td).addClass("ux-box-dateeditor-holiday")
							.removeClass("ux-box-dateeditor-selected");
                } else {
                    td.className = "";
                }

                $(td).html(showDay);
            });
        });
    },

    isDateTime: function (dateStr) {
        var r = dateStr.match(/^(\d{1,4})(-|\/)(\d{1,2})\2(\d{1,2})$/);
        if (r == null)
            return false;
        var d = new Date(r[1], r[3] - 1, r[4]);
        if (d == "NaN")
            return false;
        return (d.getFullYear() == r[1] && (d.getMonth() + 1) == r[3] && d
				.getDate() == r[4]);
    },
    isLongDateTime: function (dateStr) {
        var reg = /^(\d{1,4})(-|\/)(\d{1,2})\2(\d{1,2}) (\d{1,2}):(\d{1,2})$/;
        var r = dateStr.match(reg);
        if (r == null)
            return false;
        var d = new Date(r[1], r[3] - 1, r[4], r[5], r[6]);
        if (d == "NaN")
            return false;
        return (d.getFullYear() == r[1] && (d.getMonth() + 1) == r[3]
				&& d.getDate() == r[4] && d.getHours() == r[5] && d
				.getMinutes() == r[6]);
    },
    getFormatDate: function (date) {
        var g = this;
        if (date == "NaN")
            return null;
        var format = g.format;
        var o = {
            "M+": date.getMonth() + 1,
            "d+": date.getDate(),
            "h+": date.getHours(),
            "m+": date.getMinutes(),
            "s+": date.getSeconds(),
            "q+": Math.floor((date.getMonth() + 3) / 3),
            "S": date.getMilliseconds()
        };
        if (/(y+)/.test(format)) {
            format = format.replace(RegExp.$1, (date.getFullYear() + "")
							.substr(4 - RegExp.$1.length));
        }
        for (var k in o) {
            if (new RegExp("(" + k + ")").test(format)) {
                format = format.replace(RegExp.$1, RegExp.$1.length == 1
								? o[k]
								: ("00" + o[k]).substr(("" + o[k]).length));
            }
        }
        return format;
    },

    _getValue: function () {
        return this.usedDate;
    }
});
﻿EIAP.DateField = function () {
    return new EIAP.form.DateField(arguments[0]);
};

EIAP.form.DateField = EIAP.extend(EIAP.form.TriggerField, {
    format: "Y-m-d",
    showTime: false,
    triggerCss: "ux-date-trigger",

    initComponent: function () {
        EIAP.form.DateField.superclass.initComponent.call(this);
    },
    __getType: function () {
        return 'DateField';
    },

    __idPrev: function () {
        return 'DateField';
    },

    _extMethods: function () {
        return EIAP.form.DateField;
    },

    showList: function () {
        var g = this;
        if (!g.loading && g.list) {
            g.list.show();
            g.dom.triggerbtn.addClass(g.triggerClickCss);
            g.setListPos();
            g.showShadow();
        } else {
            g.initList();
        }
        g.calendar.bulidContent();
    },

    initList: function () {
        var g = this;
        var calendar = EIAP.Calendar({
            showTime: g.showTime,
            callback: function () {
                var date = EIAP.util.Date(arguments[0]).toDate();
                var value = g.formatValue(date);
                if (g.beforSelect) {
                    var before = {};
                    before.oldValue = g.getValue();
                    before.nowValue = value;
                    var tmp = g.beforSelect(before);
                    if (tmp == false) {
                        return;
                    }
                }
                g.setValue(value);
                g.sysValidater();
                if (g.afterSelect) {
                    g.afterSelect(value);
                }
                if (g.canClear && g.clear) {
                    var iptw = g.dom.field.width();
                    g.dom.field.width(iptw - 17);
                    g.dom.clearTrigger.show();
                    g.clear = false;
                }
                g.list.hide();
                g.shadow && g.dom.shadow && g.dom.shadow.updateShadow(g.list);
            }
        });
        calendar.parentCmp = this.id;
        var list = calendar.dom;
        $("body").append(list);
        this.list = list;
        this.calendar = calendar;
        g.dom.triggerbtn.addClass(g.triggerClickCss);
        g.setListPos();
        g.showShadow();
        g.loading = false;
    },

    setListPos: function () {
        var g = this;
        var iptpos = g.dom.field.offset();
        var ipth = g.dom.field.outerHeight();
        var top = iptpos.top + ipth;
        var listh = g.list.height();
        if ($(window).height() <= (listh + top)) {
            var tmp = (iptpos.top - ipth - listh + 20);
            if (tmp > 0) {
                top = tmp;
            }
        }
        var tw = 0;
        $('img', g.dom).each(function () {
            if ($(this).is(":visible"))
                tw += 17;
        });
        var width = g.dom.field.width() + tw + 6;
        width = width < 180 ? 180 : width;
        width = width > 200 ? 200 : width;
        g.list.css({
            "left": iptpos.left - 4,
            "top": top - 4,
            "width": width
        }).show();
        g.shadow && g.dom.shadow && g.dom.shadow.updateShadow(g.list);
    },
    reset: function () {
        EIAP.form.DateField.superclass.reset.call(this);
        this.date = "";
    },
    getValue: function () {
        return this.date;
    },
    setValue: function (value) {
        this.date = "";
        if (!value) {
            EIAP.form.DateField.superclass.setValue.call(this, "");
            return;
        }
        if (value.indexOf("Date") != -1) {
            value = EIAP.util.Date(value).format("YYYY-MM-DD HH:mm:ss");
        }
        var standardDate;
        var reg = new RegExp("\\d{1,4}", "g");
        var tmps = value.match(reg);
        if (!tmps) {
            throw new Error(g.eData + value + g.formatError);
        }
        var formatLen = this.getFormatLength();
        var len = tmps.length > formatLen ? formatLen : tmps.length;
        standardDate = tmps[0];
        for (var i = 1; i < len; i++) {
            var tmp = tmps[i];
            if (tmp.length == 1) {
                tmp = "0" + tmp;
            }
            if (i == 3) {
                standardDate += " " + tmp;
                continue;
            }
            if (i < 3) {
                standardDate += "-" + tmp;
            } else {
                standardDate += ":" + tmp;
            }
        }
        var date = EIAP.util.Date(standardDate).toDate();
        if (date.getTime()) {
            var standardValue = this.formatValue(date);
            this.date = standardValue;
            EIAP.form.DateField.superclass.setValue.call(this, standardValue);
        }
    },
    getFormatLength: function () {
        if (this.format.indexOf("m") == -1) {
            return 1;
        }
        if (this.format.indexOf("d") == -1) {
            return 2;
        }
        if (this.format.indexOf("hh") == -1) {
            return 3;
        }
        if (this.format.indexOf("mm") == -1) {
            return 4;
        }
        if (this.format.indexOf("ss") == -1) {
            return 5;
        }
        return 6;
    },
    formatValue: function (date) {
        if (date.getTime()) {
            var year = date.getFullYear();
            var month = this.transimit(date.getMonth() + 1);
            var day = this.transimit(date.getDate());
            var hour = this.transimit(date.getHours());
            var minute = this.transimit(date.getMinutes());
            var second = this.transimit(date.getSeconds());
            var dateStr = this.format.replace("Y", year);
            dateStr = dateStr.replace("mm", minute);
            dateStr = dateStr.replace("d", day);
            dateStr = dateStr.replace("m", month);
            dateStr = dateStr.replace("hh", hour);
            dateStr = dateStr.replace("ss", second);
            return dateStr;
        }
        return "";
    },
    transimit: function (num) {
        if (num < 10) {
            return "0" + num;
        }
        return num;
    }

});﻿EIAP.Button = function () {
    return new EIAP.button.Button(arguments[0]);
};
EIAP.button.Button = EIAP.extend(EIAP.UIComponent, {
    isFlat: false,
    arrowType: "arrow", //枚举值:arrow、 split
    menus: null,
    width: null,
    menuasync: true,
    btnCls: "ux-button",
    btnLeftCls: "ux-button-l",
    btnRightCls: "ux-button-r",
    btnFlatCls: "ux-button-flat",
    btnTitleCls: "ux-button-title",
    btnNoTitleCls: "ux-notitle",
    btnIconCls: "ux-hasicon",
    btnNoIconCls: "ux-noicon",
    btnHover: "ux-button-over",
    btnDisable: "ux-button-disable",
    btnSelected: "ux-button-selected",
    tipText: "",
    initComponent: function () {
        EIAP.button.Button.superclass.initComponent.call(this);
        //if (this.tipText != "" && this.tipText != null && this.tipText != undefined) {
        //    EIAP.ToolTip({ target: this.id, tipText: this.tipText });
        //}
    },
    __getType: function () {
        return 'Button';
    },
    __idPrev: function () {
        return 'Button';
    },
    _extMethods: function () {
        return EIAP.button.Button;
    },
    _render: function () {
        var g = this;
        g.dom = this.renderTo ? $(this.element) : $("<div></div>");
        g.dom.addClass(g.btnCls);
        g.isFlat && g.dom.addClass(g.btnFlatCls);
        g._bulid();
        if (g.width && !isNaN(g.width)) {
            g.dom.width(g.width);
        }
        !g.menuasync && g.renderMenu();
        g.set(g);
    },
    _bulid: function () {
        var g = this, arrowCls = "";
        if (g.menus)
            arrowCls = "ux-" + g.arrowType;
        var ditem = $('<em unselectable="on" class="' + arrowCls + '"><span class="' + g.btnTitleCls + '" title="'+g.title+'">&nbsp;</span></em><div class="' + g.btnLeftCls + '"></div><div class="' + g.btnRightCls + '"></div>');
        g.dom.append(ditem);
        g.id = g.id || EIAP.getId();
        if (g.iconCls) {
            g.dom.icon = $('<img src="' + EIAP.BLANK_IMAGE_URL + '" class="ux-icon" />');
            g.dom.icon.addClass(g.iconCls);
            g.dom.append(g.dom.icon);
            g.dom.addClass(g.btnIconCls);
        } else {
            g.dom.addClass(g.btnNoIconCls);
        }
        g.title ? $("span:first", g.dom).html(g.title) : g.dom.addClass(g.btnNoTitleCls);
        if (g.disabled)
            g.disable();
        g.initEvents();

    },
    renderMenu: function () {
        var g = this;
        if (g.menus && !g.menu && EIAP.menu.Menu) {
            g.menu = EIAP.Menu({ items: g.menus });
            g.items.push(g.menu.id);
        }
    },
    hideMenu: function () {
        var g = this;
        if (g.menu && g.dom.hasClass(g.btnSelected)) {
            g.menu.hide();
        }
    },
    initEvents: function () {
        var g = this;
        if (g.menus) {
            g.dom.click(function () {
                if (g.disabled) return false;
                $(document).click();
                g.renderMenu();
                var pos = g.dom.offset();
                var top = pos.top;
                var left = pos.left;
                g.menu && g.menu.show({
                    top: top + 22,
                    left: left - 4
                });
                g.menu.on("click", function () {
                    g.dom.removeClass(g.btnSelected);
                });
                $(document).bind('click.menu', function (evt) {
                    var el = evt.target;
                    if (el) {
                        var mitem = $(el).attr("menuitemid") || $(el).parent().attr("menuitemid");
                        if (mitem && EIAP.getCmp(mitem).disabled) return;
                    }
                    g.menu.fireEvent("click");
                });
                g.dom.addClass(g.btnSelected);
                return false;
            });
        }
        else if (g.handler && typeof g.handler == 'function') {
            g.dom.click(function () {
                if (g.disabled) return false;
                $(document).click();
                g.handler.call(this, g);
                return false;
            });
        }
        g.dom.hover(function () {
            $(this).addClass(g.btnHover);
        }, function () {
            $(this).removeClass(g.btnHover);
        });
    },
    disable: function () {
        this.disabled = true;
        this.dom.addClass(this.btnDisable);
    },
    enable: function () {
        this.disabled = false;
        this.dom.removeClass(this.btnDisable);
    },
    setTitle: function () {
        var g = this, ags = arguments;
        if (ags.length > 0) {
            g.title = ags[0];
            $("span:first", g.dom).html(ags[0]);
        }
    }
});
﻿EIAP.Drag = EIAP.extend(EIAP.UIComponent, {
    idAttrName: 'eiapuidragid',
    hasElement: false,
    onStartDrag: false,
    onDrag: false,
    onStopDrag: false,
    dragHandler: null,
    //代理 拖动时的主体,可以是'clone'或者是函数,放回jQuery 对象
    proxy: null,
    revert: false,
    animate: true,
    onRevert: null,
    onEndRevert: null,
    //接收区域 jQuery对象或者jQuery选择字符
    receive: null,
    //进入区域
    onDragEnter: null,
    //在区域移动
    onDragOver: null,
    //离开区域
    onDragLeave: null,
    //在区域释放
    onDrop: null,
    disabled: false,
    proxyX: null,     //代理相对鼠标指针的位置,如果不设置则对应target的left
    proxyY: null,
    initComponent: function () {
        EIAP.Drag.superclass.initComponent.call(this);
    },
    __getType: function () {
        return 'Drag';
    },
    __idPrev: function () {
        return 'Drag';
    },
    _render: function () {
        var g = this, p = g.options;
        this.set(g);
        g.cursor = "move";
        g.dragHandler.css('cursor', g.cursor);
        g.dragHandler.bind('mousedown.drag', function (e) {
            if (g.disabled) return;
            if (e.button == 2) return;
            g._start.call(g, e);
        }).bind('mousemove.drag', function () {
            if (g.disabled) return;
            g.dragHandler.css('cursor', g.cursor);
        });
    },
    _rendered: function () {
        this.target.eiapuidragid = this.id;
    },
    _start: function (e) {
        var g = this, p = g.options;
        if (g.reverting) return;
        if (g.disabled) return;
        g.current = {
            target: g.target,
            left: g.target.offset().left,
            top: g.target.offset().top,
            startX: e.pageX || e.screenX,
            startY: e.pageY || e.clientY
        };
        if (g.trigger('startDrag', [g.current, e]) == false) return false;
        g.cursor = "move";
        g._createProxy(p.proxy, e);
        //代理没有创建成功
        if (p.proxy && !g.proxy) return false;
        (g.proxy || g.dragHandler).css('cursor', g.cursor);
        $(document).bind("selectstart.drag", function () { return false; });
        $(document).bind('mousemove.drag', function () {
            g._drag.apply(g, arguments);
        });
        EIAP.draggable.dragging = true;
        $(document).bind('mouseup.drag', function () {
            EIAP.draggable.dragging = false;
            g._stop.apply(g, arguments);
        });
    },
    _drag: function (e) {
        var g = this;
        if (!g.current) return;
        var pageX = e.pageX || e.screenX;
        var pageY = e.pageY || e.screenY;
        g.current.diffX = pageX - g.current.startX;
        g.current.diffY = pageY - g.current.startY;
        (g.proxy || g.dragHandler).css('cursor', g.cursor);
        if (g.receive) {
            g.receive.each(function (i, obj) {
                var receive = $(obj);
                var xy = receive.offset();
                if (pageX > xy.left && pageX < xy.left + receive.width()
                    && pageY > xy.top && pageY < xy.top + receive.height()) {
                    if (!g.receiveEntered[i]) {
                        g.receiveEntered[i] = true;
                        g.trigger('dragEnter', [obj, g.proxy || g.target, e]);
                    }
                    else {
                        g.trigger('dragOver', [obj, g.proxy || g.target, e]);
                    }
                }
                else if (g.receiveEntered[i]) {
                    g.receiveEntered[i] = false;
                    g.trigger('dragLeave', [obj, g.proxy || g.target, e]);
                }
            });
        }
        if (g.hasBind('drag')) {
            if (g.trigger('drag', [g.current, e]) != false) {
                g._applyDrag();
            }
            else {
                g._removeProxy();
            }
        }
        else {
            g._applyDrag();
        }
    },
    _stop: function (e) {
        var g = this;
        $(document).unbind('mousemove.drag');
        $(document).unbind('mouseup.drag');
        $(document).unbind("selectstart.drag");
        if (g.receive) {
            g.receive.each(function (i, obj) {
                if (g.receiveEntered[i]) {
                    g.trigger('drop', [obj, g.proxy || g.target, e]);
                }
            });
        }
        if (g.proxy) {
            if (g.revert) {
                if (g.hasBind('revert')) {
                    if (g.trigger('revert', [g.current, e]) != false)
                        g._revert(e);
                    else
                        g._removeProxy();
                }
                else {
                    g._revert(e);
                }
            }
            else {
                g._applyDrag(g.target);
                g._removeProxy();
            }
        }
        g.cursor = 'move';
        g.trigger('stopDrag', [g.current, e]);
        g.current = null;
        g.dragHandler.css('cursor', g.cursor);
    },
    _revert: function (e) {
        var g = this;
        g.reverting = true;
        g.proxy.animate({
            left: g.current.left,
            top: g.current.top
        }, function () {
            g.reverting = false;
            g._removeProxy();
            g.trigger('endRevert', [g.current, e]);
            g.current = null;
        });
    },
    _applyDrag: function (applyResultBody) {
        var g = this;
        applyResultBody = applyResultBody || g.proxy || g.target;
        var cur = {};
        var noproxy = applyResultBody == g.target;
        if (g.current.diffX) {
            if (noproxy || g.proxyX == null)
                cur.left = g.current.left + g.current.diffX;
            else
                cur.left = g.current.startX + g.proxyX + g.current.diffX;
        }
        if (g.current.diffY) {
            if (noproxy || g.proxyY == null)
                cur.top = g.current.top + g.current.diffY;
            else
                cur.top = g.current.startY + g.proxyY + g.current.diffY;
            if (cur.top < 0)
                cur.top = 0;
        }
        if (applyResultBody == g.target && g.proxy && g.animate) {
            g.reverting = true;
            applyResultBody.animate(cur, function () {
                g.reverting = false;
            });
        }
        else {
            applyResultBody.css(cur);
        }
    },
    _setReceive: function (receive) {
        this.receiveEntered = {};
        if (!receive) return;
        if (typeof receive == 'string')
            this.receive = $(receive);
        else
            this.receive = receive;
    },
    _setDragHandler: function (dragHandler) {
        var g = this;
        if (!dragHandler)
            g.dragHandler = $(g.target);
        else
            g.dragHandler = (typeof dragHandler == 'string' ? $(dragHandler, g.target) : dragHandler);
    },
    _setTarget: function (target) {
        this.target = $(target);
    },
    _setCursor: function (cursor) {
        this.cursor = cursor;
        (this.proxy || this.dragHandler).css('cursor', cursor);
    },
    _createProxy: function (proxy, e) {
        if (!proxy) return;
        var g = this;
        if (typeof proxy == 'function') {
            g.proxy = proxy.call(g.target, g, e);
        }
        else if (proxy == 'clone') {
            g.proxy = g.target.clone().css('position', 'absolute');
            g.proxy.appendTo('body');
        }
        else {
            var targetcmp = EIAP.get(g.target);
            var type = targetcmp.renderType || targetcmp.type.toLowerCase();
            var tmpghost = g.target.clone();
            g.proxy = $("<div class='ux-dragable'></div>");
            targetcmp.buttonbox && $(".ux-window-buttons", tmpghost).empty();
            $(".ux-" + type + "-content", tmpghost).css("visibility", "hidden");
            g.proxy.append(tmpghost.html());
            g.proxy.width(g.target.width()).height(g.target.height());
            g.proxy.attr("dragid", g.id).appendTo('body');
        }
        g.proxy.css({
            left: g.proxyX == null ? g.current.left : g.current.startX + g.proxyX,
            top: g.proxyY == null ? g.current.top : g.current.startY + g.proxyY
        }).show();
    },
    _removeProxy: function () {
        var g = this;
        if (g.proxy) {
            g.proxy.remove();
            EIAP.remove(g.id);
            g.proxy = null;
        }
    }
});﻿EIAP.Resizable = EIAP.extend(EIAP.UIComponent, {
    idAttrName: 'eiapuiresizableid',
    hasElement: false,
    propertyToElemnt: 'target',
    handles: 'n, e, s, w, ne, se, sw, nw',
    maxWidth: 2000,
    maxHeight: 2000,
    minWidth: 20,
    minHeight: 20,
    scope: 3,
    animate: false,
    onStartResize: function (e) { },
    onResize: function (e) { },
    onStopResize: function (e) { },
    onEndResize: null,
    initComponent: function () {
        EIAP.Resizable.superclass.initComponent.call(this);
    },
    __getType: function () {
        return 'Resizable';
    },
    __idPrev: function () {
        return 'Resizable';
    },
    _render: function () {
        var g = this;
        g.target = $(g.target);
        g.set(g);
        g.target.mousemove(function (e) {
            if (g.disabled) return;
            g.dir = g._getDir(e);
            if (g.dir)
                g.target.css('cursor', g.dir + '-resize');
            else if (g.target.css('cursor').indexOf('-resize') > 0)
                g.target.css('cursor', 'default');
            if (g.target.eiapuidragid) {
                var drag = EIAP.get(g.target.eiapuidragid);
                if (drag && g.dir) {
                    drag.set('disabled', true);
                } else if (drag) {
                    drag.set('disabled', false);
                }
            }
        }).mousedown(function (e) {
            if (g.disabled) return;
            if (g.dir) {
                g._start(e);
            }
        });
    },
    _rendered: function () {
        this.target.eiapuiresizableid = this.id;
    },
    _getDir: function (e) {
        var g = this;
        var dir = '';
        var xy = g.target.offset();
        var width = g.target.width();
        var height = g.target.height();
        var scope = g.scope;
        var pageX = e.pageX || e.screenX;
        var pageY = e.pageY || e.screenY;
        if (pageY >= xy.top && pageY < xy.top + scope) {
            dir += 'n';
        }
        else if (pageY <= xy.top + height && pageY > xy.top + height - scope) {
            dir += 's';
        }
        if (pageX >= xy.left && pageX < xy.left + scope) {
            dir += 'w';
        }
        else if (pageX <= xy.left + width && pageX > xy.left + width - scope) {
            dir += 'e';
        }
        if (g.handles == "all" || dir == "") return dir;
        if ($.inArray(dir, g.handles) != -1) return dir;
        return '';
    },
    _setHandles: function (handles) {
        if (!handles) return;
        this.handles = handles.replace(/(\s*)/g, '').split(',');
    },
    _createProxy: function () {
        var g = this;
        g.proxy = $('<div class="ux-resizable"></div>');
        g.proxy.width(g.target.width()).height(g.target.height());
        g.proxy.attr("resizableid", g.id).appendTo('body');
    },
    _removeProxy: function () {
        var g = this;
        if (g.proxy) {
            g.proxy.remove();
            g.proxy = null;
        }
    },
    _start: function (e) {
        var g = this;
        g._createProxy();
        g.proxy.css({
            left: g.target.offset().left,
            top: g.target.offset().top,
            position: 'absolute'
        });
        g.current = {
            dir: g.dir,
            left: g.target.offset().left,
            top: g.target.offset().top,
            startX: e.pageX || e.screenX,
            startY: e.pageY || e.clientY,
            width: g.target.width(),
            height: g.target.height()
        };
        $(document).bind("selectstart.resizable", function () { return false; });
        $(document).bind('mouseup.resizable', function () {
            g._stop.apply(g, arguments);
        });
        $(document).bind('mousemove.resizable', function () {
            g._drag.apply(g, arguments);
        });
        g.proxy.show();
        g.trigger('startResize', [g.current, e]);
    },
    changeBy: {
        t: ['n', 'ne', 'nw'],
        l: ['w', 'sw', 'nw'],
        w: ['w', 'sw', 'nw', 'e', 'ne', 'se'],
        h: ['n', 'ne', 'nw', 's', 'se', 'sw']
    },
    _drag: function (e) {
        var g = this;
        if (!g.current) return;
        if (!g.proxy) return;
        g.proxy.css('cursor', g.current.dir == '' ? 'default' : g.current.dir + '-resize');
        var pageX = e.pageX || e.screenX;
        var pageY = e.pageY || e.screenY;
        g.current.diffX = pageX - g.current.startX;
        g.current.diffY = pageY - g.current.startY;
        g._applyResize(g.proxy);
        g.trigger('resize', [g.current, e]);
    },
    _stop: function (e) {
        var g = this, p = this.options;

        if (g.hasBind('stopResize')) {
            if (g.trigger('stopResize', [g.current, e]) != false)
                g._applyResize();
        }
        else {
            g._applyResize();
        }
        g._removeProxy();
        g.trigger('endResize', [g.current, e]);
        $(document).unbind("selectstart.resizable");
        $(document).unbind('mousemove.resizable');
        $(document).unbind('mouseup.resizable');
    },
    _applyResize: function (applyResultBody) {
        var g = this;
        var cur = {
            left: g.current.left,
            top: g.current.top,
            width: g.current.width,
            height: g.current.height
        };
        var applyToTarget = false;
        if (!applyResultBody) {
            applyResultBody = g.target;
            applyToTarget = true;
            if (!isNaN(parseInt(g.target.css('top'))))
                cur.top = parseInt(g.target.css('top'));
            else
                cur.top = 0;
            if (!isNaN(parseInt(g.target.css('left'))))
                cur.left = parseInt(g.target.css('left'));
            else
                cur.left = 0;
        }
        if ($.inArray(g.current.dir, g.changeBy.l) > -1) {
            cur.left += g.current.diffX;
            g.current.diffLeft = g.current.diffX;

        }
        else if (applyToTarget) {
            delete cur.left;
        }
        if ($.inArray(g.current.dir, g.changeBy.t) > -1) {
            cur.top += g.current.diffY;
            g.current.diffTop = g.current.diffY;
        }
        else if (applyToTarget) {
            delete cur.top;
        }
        if ($.inArray(g.current.dir, g.changeBy.w) > -1) {
            cur.width += (g.current.dir.indexOf('w') == -1 ? 1 : -1) * g.current.diffX;
            g.current.newWidth = cur.width;
        }
        else if (applyToTarget) {
            delete cur.width;
        }
        if ($.inArray(g.current.dir, g.changeBy.h) > -1) {
            cur.height += (g.current.dir.indexOf('n') == -1 ? 1 : -1) * g.current.diffY;
            g.current.newHeight = cur.height;
        }
        else if (applyToTarget) {
            delete cur.height;
        }
        if (applyToTarget && g.animate)
            applyResultBody.animate(cur);
        else
            applyResultBody.css(cur);
    }
});
﻿EIAP.Shadow = EIAP.Shadow = function () {
    return new EIAP.shadow.Shadow(arguments[0]);
};
EIAP.shadow.Shadow = EIAP.extend(EIAP.UIComponent, {
    isLoadMask: false,
    initComponent: function () {
        EIAP.shadow.Shadow.superclass.initComponent.call(this);
    },
    __getType: function () {
        return 'Shadow';
    },
    __idPrev: function () {
        return 'Shadow';
    },
    _extMethods: function () {
        return EIAP.shadow.Shadow;
    },
    _render: function () {
        var g = this;
        g.dom = $('<div class="ux-shadow"><div class="xst"><div class="xstl"></div><div class="xstc"></div><div class="xstr"></div></div><div class="xsc"><div class="xsml"></div><div class="xsmc"></div><div class="xsmr"></div></div><div class="xsb"><div class="xsbl"></div><div class="xsbc"></div><div class="xsbr"></div></div></div>').insertAfter(g.target);

    },
    updateShadow: function (windom) {
        var g = this;
        if (!windom) return;
        var winpos = g.isLoadMask ? windom.position() : windom.offset();
        g.dom.css({
            left: winpos.left - 4,
            top: winpos.top,
            width: windom.outerWidth() + 8,
            height: windom.outerHeight() + 4
        });
        $('.xstc', g.dom).width(windom.outerWidth() - 4);
        $('.xsc', g.dom).height(windom.outerHeight() - 8);
        $('.xsmc', g.dom).width(windom.outerWidth() - 4);
        $('.xsbc', g.dom).width(windom.outerWidth() - 4);
        var zidx = windom.css("z-index");
        if (zidx) {
            g.setZIndex(zidx);
        }
        if (windom.is(":visible"))
            g.dom.show();
        else
            g.dom.hide();
    },
    hide: function () {
        this.dom.hide();
    },
    remove: function () {
        this.dom.remove();
    },
    setZIndex: function (index) {
        var g = this;
        var zidx = index - 5;
        g.dom.css("z-index", zidx);
    }
});﻿EIAP.LoadMask = function (cmp, cfg) {
    return new EIAP.LoadingMask(cmp, cfg);
};
EIAP.LoadingMask = function (cmp, cfg) {
    if (cmp && cmp instanceof EIAP.UIComponent) {
        this.isCmp = true;
        this.Cmp = cmp;
        this.targetDom = cmp.dom;
    }
    else {
        this.targetDom = EIAP.getBody();
    }
    EIAP.apply(this, cfg);
    if (this.store) {
        var before = this.store.beforeLoad;
        var after = this.store.afterLoad;
        this.stroe.beforeLoad = function () {
            this.onBeforeLoad();
            before(arguments[0]);
        };
        this.removeMask = false;
    } else {
        this.removeMask = true;
    }
};
EIAP.LoadingMask.prototype = {
    msg: 'Loading...',
    isCmp: false,
    disabled: false,
    disable: function () {
        this.disabled = true;
    },
    enable: function () {
        this.disabled = false;
    },
    // private
    onLoaded: function () {
        if (!this.mask) return;
        if (this.removeMask) {
            this.mask.remove();
            this.maskMsg.remove();
            if (this.maskMsg.shadow) {
                EIAP.remove(this.maskMsg.shadow);
            }
            this.mask = null;
        } else {
            this.mask.hide();
            this.maskMsg.hide();
            if (this.maskMsg.shadow) {
                this.maskMsg.shadow.updateShadow(this.maskMsg);
            }
        }
    },
    // private
    onBeforeLoad: function () {
        if (!this.disabled) {
            if (this.mask) {
                this.mask.show();
                this.maskMsg.show();
            } else {
                this.mask = $('<div class="ux-mask"></div>');
                this.maskMsg = $('<div class="ux-mask-msg"><div class="ux-msg-text">' + this.msg + '</div></div>');
                if (this.isCmp) {
                    var mskdom = this.targetDom.content ? this.targetDom.content.bwrap : this.targetDom;
                    mskdom.append(this.mask).append(this.maskMsg);
                } else {
                    this.targetDom.append(this.mask).append(this.maskMsg);
                }
                this.setPosition();
                this.setShadow();
                var g = this;
                $(window).resize(function () {
                    g.setPosition();
                    g.setShadow();
                });
            }
        }
    },
    show: function () {
        this.onBeforeLoad();
    },
    hide: function () {
        this.onLoaded();
    },
    setMsg: function () {
        if (arguments.length == 1) {
            $('div.ux-msg-text', this.maskMsg).html(arguments[0]);
            this.msg = arguments[0];
            this.setPosition();
            this.setShadow();
        }
    },
    setShadow: function () {
        if (EIAP.Shadow && !this.maskMsg.shadow) {
            this.maskMsg.shadow = new EIAP.Shadow({ target: this.maskMsg, isLoadMask: true });
        }
        this.maskMsg.shadow.updateShadow(this.maskMsg);
    },
    setPosition: function () {
        var mask = this.maskMsg;
        if (this.isCmp) {
            var dom = this.targetDom;
            var left = 0.5 * (dom.innerWidth() - mask.width()) - 4;
            var mskdom = dom.content ? dom.content : dom;
            var top = 0.5 * (mskdom.innerHeight() - mask.height());
        } else {
            left = 0.5 * ($(window).width() - mask.width());
            top = 0.5 * ($(window).height() - mask.height()) + $(window).scrollTop() - 30;
        }
        mask.css({
            left: left,
            top: top
        });
    }
};
﻿EIAP.MenuItem = function () {
    return new EIAP.menu.MenuItem(arguments[0]);
};

EIAP.menu.MenuItem = EIAP.extend(EIAP.UIComponent, {
    defaultType: 'MenuItem',
    disableCls: "ux-menu-item-disable",
    initComponent: function () {
        EIAP.menu.MenuItem.superclass.initComponent.call(this);
    },
    __getType: function () {
        return 'MenuItem';
    },
    __idPrev: function () {
        return 'MenuItem';
    },
    _extendMethods: function () {
        return EIAP.menu.MenuItem;
    },
    _render: function () {
        var g = this;
        g.dom = this.randerTo ? $(this.element) : $('<div class="ux-menu-item"><div class="ux-menu-item-text"></div></div>');
        g._bulid();
        g.set(g);
    },
    _bulid: function () {
        var g = this;
        g.id = g.id || EIAP.getId();
        g.dom.attr("menuitemid", g.id);
        g.title && $(">.ux-menu-item-text:first", g.dom).html(g.title);
        g.iconCls && g.dom.prepend('<div class="ux-menu-item-icon ' + g.iconCls + '"></div>');
        if (g.disabled)
            g.dom.addClass(g.disableCls);
        if (g.handler && typeof g.handler == 'function') {
            g.dom.click(function () {
                if (g.disabled) return;
                g.handler.call(this, g);
            });
        }
        g.dom.hover(function () {
            if (g.disabled) return;
            var itemtop = $(this).offset().top;
            var tmpmenu = EIAP.managers[g.parentCmp];
            if (tmpmenu == undefined) {
                tmpmenu = g._getMenuByItem(g);
            }
            var menuover = $("> .ux-menu-over:first", tmpmenu.menu);
            var top = itemtop - tmpmenu.menu.offset().top;
            menuover.css({ top: top });
            tmpmenu.hideAllSubMenu(tmpmenu.menu);
            if (g.items) {
                var eiapuimenutemid = $(this).attr("eiapuimenutemid");
                if (!eiapuimenutemid) return;
                var submenu = EIAP.managers[g.subMenuId];
                if (submenu) {
                    submenu.show({ top: itemtop, left: $(this).offset().left + $(this).width() - 5 }, submenu.menu);
                    submenu.menu.showedSubMenu = true;
                }
            }
        }, function () {
            if (g.disabled) return;
            if (g.items) {
                var eiapuimenutemid = $(this).attr("eiapuimenutemid");
                if (!eiapuimenutemid) return;
            };
        });
    },
    _getMenuByItem: function (item) {
        var menuid = item.dom.parent().parent().attr("eiapuiid");
        var menu = null;
        if (menuid) {
            menu = EIAP.managers[menuid];
        }
        return menu;
    },
    disable: function () {
        this.disabled = true;
        this.dom.addClass(this.disableCls);
    },
    enable: function () {
        this.disabled = false;
        this.dom.removeClass(this.disableCls);
    },
    setTitle: function () {
        var g = this, ags = arguments;
        if (ags.length > 0) {
            g.title = ags[0];
            $(">.ux-menu-item-text:first", g.dom).html(ags[0]);
        }
    }
});﻿EIAP.Menu = function () {
    return new EIAP.menu.Menu(arguments[0]);
};

EIAP.menu.Menu = EIAP.extend(EIAP.UIComponent, {
    width: 140,
    top: 0,
    left: 0,
    items:null,
    shadow: true,
    defaultType: 'MenuItem',
    initComponent: function () {
        EIAP.menu.Menu.superclass.initComponent.call(this);
    },
    __getType: function () {
        return 'Menu';
    },
    __idPrev: function () {
        return 'Menu';
    },
    _extendMethods: function () {
        return EIAP.menu.Menu;
    },
    _render: function () {
        var g = this;
        g.menuItemCount = 0;
        //全部菜单
        g.menus = {};
        //顶级菜单
        g.menu = g.createMenu(g.parentMenuItemID);
        g.element = g.menu[0];
        g.menu.css({ top: g.top, left: g.left, width: g.width });
        g.options.items && g.addItems(g.options.items);
        $(document).bind('click.menu', function (evt) {
            for (var menuid in g.menus) {
                var menu = g.menus[menuid];
                var el = evt.target;
                if (el) {
                    var mitem = $(el).attr("menuitemid") || $(el).parent().attr("menuitemid");
                    if (mitem && EIAP.getCmp(mitem).disabled) return;
                }
                if (!menu) return;
                menu.hide();
                if (menu.shadow) menu.shadow.hide();
            }
        });
        g.set(g);
    },
    show: function (options, menu) {
        var g = this;
        if (options) {
            var left = options.left, top = options.top;
            if (menu == undefined) menu = g.menu;
            if (left != undefined) {
                var ww = $(window).width();
                if (ww <= (left + menu.width())) {
                    left = (ww - menu.width() - 8);
                }
                menu.css({ left: left });
            }
            if (top != undefined) {
                var wh = $(window).height();
                if (wh <= (top + menu.height())) {
                    top = (wh - menu.height() + 5);
                }
                menu.css({ top: top });
            }
            menu.animate({ left: left + 4, top: top, opacity: 'show' }, 200, function () {
                menu.shadow && menu.shadow.updateShadow(menu);
            });
        }
    },
    hide: function (menu) {
        var g = this;
        if (menu == undefined) menu = g.menu;
        g.hideAllSubMenu(menu);
        menu.hide();
        menu.shadow && menu.shadow.updateShadow(menu);
    },
    toggle: function () {
        var g = this;
        g.menu.toggle();
        menu.shadow && menu.shadow.updateShadow(g.menu);
    },
    removeItem: function (itemid) {
        var g = this;
        $('> .ux-menu-item[menuitemid="' + itemid + '"]', g.menu.menuItems).remove();
    },
    setEnabled: function (itemid) {
        EIAP.getCmp(itemid).enable();
    },
    setDisabled: function (itemid) {
        EIAP.getCmp(itemid).disable();
    },
    isEnable: function (itemid) {
        var g = this;
        return !$('> .ux-menu-item[menuitemid="' + itemid + '"]', g.menu.menuItems).hasClass("ux-menu-item-disable");
    },
    getItemCount: function () {
        var g = this;
        return $("> .ux-menu-item", g.menu.menuItems).length;
    },
    addItems: function (items, menu) {
        var g = this;
        if (!items) return;
        if (menu == undefined) menu = g.menu;
        this.items = [];
        for (var i = 0; i < items.length; i++) {
            var curitem = items[i];
            var xtype = curitem.xtype ? curitem.xtype : g.defaultType;
            if (menu.menuItems == undefined) {
                menu.menuItems = $("> .ux-menu-inner:first", menu.menu);
                menu.parentCmp = g.id;
            }
            if (curitem == "-") {
                menu.menuItems.append('<div class="ux-menu-item-line">&nbsp;</div>');
                continue;
            }
            if (xtype) {
                var cmp = eval("EIAP." + xtype);
                var menuitem = cmp.call(cmp, curitem);
                if (xtype != "MenuItem") {
                    var newmenuitem = EIAP.MenuItem();
                    newmenuitem.items = [];
                    newmenuitem.parentCmp = g.id;
                    $("> .ux-menu-item-text", newmenuitem.dom).append(menuitem.dom);
                    newmenuitem.items.push(menuitem.id);
                    menuitem = newmenuitem;
                }
                this.items.push(menuitem.id);
                menu.menuItems.append(menuitem.dom);
                menuitem.dom.attr("eiapuimenutemid", ++g.menuItemCount);
                if (curitem.items) {
                    menuitem.items = [];
                    menuitem.dom.append('<div class="ux-menu-item-arrow"></div>');
                    var options = EIAP.apply({}, g);
                    options.id = "";
                    options.items = curitem.items;
                    options.parentMenuItemID = menuitem.dom.attr("eiapuimenutemid");
                    var newmenu = EIAP.Menu(options);
                    menuitem.subMenuId = newmenu.id;
                    menuitem.items.push(newmenu.id);
                }
            }
        }
    },
    hideAllSubMenu: function (menu) {
        var g = this;
        if (menu == undefined) menu = g.menu;
        $("> .ux-menu-item", menu.menuItems).each(function () {
            if ($("> .ux-menu-item-arrow", this).length > 0) {
                var menuitemid = $(this).attr("menuitemid");
                var menuitem = EIAP.managers[menuitemid];
                if (!menuitem.subMenuId) return;
                var submenu = EIAP.managers[menuitem.subMenuId];
                submenu.menu && g.hide(submenu.menu);
            }
        });
        menu.showedSubMenu = false;
    },
    createMenu: function (parentMenuItemId) {
        var g = this;
        var menu = $('<div class="ux-menu" style="display:none"><div class="ux-menu-yline"></div><div class="ux-menu-over"><div class="ux-menu-over-l"></div> <div class="ux-menu-over-r"></div></div><div class="ux-menu-inner"></div></div>');
        parentMenuItemId && menu.attr("eiapuiparentmenuitemid", parentMenuItemId);
        menu.menuItems = $("> .ux-menu-inner:first", menu);
        menu.appendTo('body');
        if (g.shadow && EIAP.Shadow) {
            menu.shadow = new EIAP.Shadow({ target: menu });
            g.items.push(menu.shadow.id);
            menu.shadow.updateShadow(menu);
        }
        menu.hover(null, function () {
            if (!menu.showedSubMenu)
                $("> .ux-menu-over:first", menu).css({ top: -24 });
        });
        if (parentMenuItemId)
            g.menus[parentMenuItemId] = menu;
        else
            g.menus[0] = menu;
        return menu;
    },
    remove:function() {
        this.menu.shadow.dom.remove();
    }
});
﻿EIAP.Container = function () {
    return new EIAP.panel.Container(arguments[0]);
};
EIAP.panel.Container = EIAP.extend(EIAP.UIComponent, {
    layout: "form",
    space: 2,
    padding: 4,
    test: [],
    border: false,
    width: "100%",
    height: "100%",
    defaultStyle: null,
    domCss: "ux-container",
    itemCss: "ux-column-item",
    columnCss: "ux-column-layout",
    rowCss: "ux-line-row",
    cellCss: "ux-line-cell",
    resize:null,
    initComponent: function () {
        EIAP.panel.Container.superclass.initComponent.call(this);
    },

    __getType: function () {
        return 'Container';
    },

    __idPrev: function () {
        return 'Container';
    },

    _extMethods: function () {
        return EIAP.panel.Container;
    },

    _render: function () {
        var g = this;
        g.dom = g.renderTo ? $(g.element) : $("<div></div>");
        g.dom.addClass(g.domCss);
        if (g.padding) {
            g.dom.css({ padding: g.padding });
        }
        g.setWidth(g.width);
        g.setHeight(g.height);
        !g.border && g.dom.addClass("ux-panel-noborder");
    },
    setWidth: function () {
        var width = parseFloat(arguments[0]);
        if (width) {
            if (typeof arguments[0] == "string" && arguments[0].indexOf("%") > -1) {
                width /= 100;
                width *= this.dom.parent().width();
            }
            width -= parseFloat(this.dom.css("paddingLeft")) || 0;
            width -= parseFloat(this.dom.css("paddingRight")) || 0;
            width -= parseFloat(this.dom.css("marginLeft")) || 0;
            width -= parseFloat(this.dom.css("marginRight")) || 0;
            if (this.border) {
                width -= 2;
            }
            this.dom.width(width);
            this.width = arguments[0];
        }
    },
    setHeight: function () {
        var height = parseFloat(arguments[0]);
        var parent = this.dom.parent();
        if (height) {
            if (!parent.hasClass(this.rowCss) && !parent.hasClass(this.cellCss) && !parent.hasClass(this.columnCss)) {
                var pheight = parent.height();
                if (typeof arguments[0] == "string" && arguments[0].indexOf("%") > -1) {
                    height /= 100;
                    if (parent[0].tagName.toLowerCase() == "body") {
                        pheight = $(window).height();
                        pheight -= (parseFloat(parent.css("marginTop")) || 0);
                        pheight -= parseFloat(parent.css("marginBottom")) || 0;
                    }
                    height *= pheight;
                }
                height -= parseFloat(this.dom.css("marginTop")) || 0;
                height -= parseFloat(this.dom.css("marginBottom")) || 0;
                if (this.border) {
                    height -= 2;
                }
                if (this.padding) {
                    height -= 2 * this.padding;
                }
                this.dom.height(height);
                this.height = arguments[0];
            }
        } else {
            this.dom.css("height", "auto");
            if (this.dom.height() > parent.height()) {
                var width = this.dom.width();
                this.dom.width(width - 17);
            }
        }
    },
    doLayout: function () {
        var type = arguments[0];
        switch (this.layout) {
            case "form":
                if (type == "init")
                    EIAP.FormLayout(this, "layout");
                else {
                    EIAP.FormLayout(this, "resize");
                }
                break;
            case "column":
                if (type == "init")
                    EIAP.ColumnLayout(this, "layout");
                else {
                    EIAP.ColumnLayout(this, "resize");
                }
                break;
            case "border":
                if (type == "init")
                    EIAP.BorderLayout(this, "layout");
                else {
                    EIAP.BorderLayout(this, "resize");
                }
                break;
            case "accordion":
                if (type == "init")
                    EIAP.AccordionLayout(this, "layout");
                else {
                    EIAP.AccordionLayout(this, "resize");
                }
                break;
            case "auto":
                if (type == "init")
                    EIAP.AutoLayout(this, "layout");
                else {
                    EIAP.AutoLayout(this, "resize");
                }
                break;
            default:
                if (type == "init")
                    EIAP.FormLayout(this, "layout");
                else {
                    EIAP.FormLayout(this, "resize");
                }
        }
    },
    addItems: function () {
        if (this.html) {
            return;
        }
        var items = this.options.items;
        if (items) {
            this.doLayout("init");
        }
    },

    onResize: function () {
        var g = this;
        if (typeof g.width == "string" && g.width.indexOf("%") > -1) {
            g.setWidth(g.width);
        }
        if (typeof g.height == "string" && g.height.indexOf("%") > -1) {
            g.setHeight(g.height);
        }
        g.doResize();
        this.resize && this.resize();
    },

    doResize: function () {
        var items = this.items;
        if (items) {
            this.doLayout("resize");
        }
    }

});﻿EIAP.Panel = function () {
    return new EIAP.panel.Panel(arguments[0]);
};

EIAP.panel.Panel = EIAP.extend(EIAP.panel.Container, {
    title: "",
    isBubble: false,
    tbar: null,
    bbar: null,
    footer: false,
    isOverFlow: true,
    collapsible: false,
    boxCss: "ux-panel",
    contentCss: "ux-panel-content",
    hearderCss: "ux-panel-header",
    toolBoxCss: "ux-header-toolbox",
    toolsCss: "ux-header-tools",
    iconCss: "ux-panel-icon",
    innerCss: "ux-header-inner",
    bwrapCss: "ux-panel-bwrap",
    collapsedCss: "ux-panel-collapsed",
    toggleCss: "ux-panel-toggle",
    html: null,
    afterCollapse: null,
    afterExpand: null,
    initComponent: function () {
        EIAP.panel.Panel.superclass.initComponent.call(this);
    },
    __getType: function () {
        return 'Panel';
    },
    __idPrev: function () {
        return 'Panel';
    },
    _extMethods: function () {
        return EIAP.panel.Panel;
    },
    _render: function () {
        var g = this;
        g.dom = g.renderTo ? $(g.element) : $("<div></div>");
        g.dom.addClass(g.boxCss);
        g.initContent();
        g.initHeader();
        if (g.isBubble) {
            g.setBubble(arguments[0]);
        }
        if (g.tbar) {
            g.tbar = g.setToolBar("tbar").id;
            g.items.push(g.tbar);
        }
        if (g.bbar) {
            g.bbar = g.setToolBar("bbar").id;
            g.items.push(g.bbar);
        }
        !g.border && g.dom.addClass("ux-panel-noborder");
        g.setWidth(g.width);
        g.setHeight(g.height);
    },
    initContent: function () {
        var g = this;
        var content = $('<div class="' + g.contentCss + '"></div>');
        if (g.padding) {
            content.css({ padding: g.padding });
        }
        if (g.html) {
            content.append(g.html);
        }
        g.dom.append(content);
        g.dom.content = content;
        g.dom.content.bwrap = g.dom.content.wrap('<div class="' + g.bwrapCss + '"></div>').parent();

    },
    initHeader: function () {
        var g = this;
        var header = $('<div class="' + g.hearderCss + '"></div>');
        header.toolbox = $('<div class="' + g.toolBoxCss + '"></div>').bind("click", function () {
            return false;
        });
        header.append(header.toolbox);
        if (g.iconCls) {
            var headerIcon = $('<div></div>');
            headerIcon.addClass(g.iconCss).addClass(g.iconCls);
            header.append(headerIcon);
        }
        var title = $('<div class="' + g.innerCss + '" title="' + g.title + '">' + g.title + '</div>');
        if (!g.title && !g.iconCls) {
            header.hide();
        }
        header.append(title);
        if (g.collapsible) {
            header.toolbox.addClass(g.toolsCss).addClass(g.toggleCss);
            if (g.collapse && g.expand) {
                header.toolbox.toggle(function () {
                    g.collapse();
                }, function () {
                    g.expand();
                });
            }
            header.show();
        }
        g.dom.header = header;
        g.dom.header.title = title;
        g.dom.prepend(header);
    },
    collapse: function () {
        var g = this;
        g.dom.content.bwrap.slideUp("normal", function () {
            g.dom.header.addClass(g.collapsedCss);
            g.afterCollapse && g.afterCollapse();
        });
    },
    expand: function () {
        var g = this;
        g.dom.content.bwrap.slideDown("normal", function () {
            g.dom.header.removeClass(g.collapsedCss);
            g.afterExpand && g.afterExpand();
        });
    },
    setToolBar: function () {
        var g = this;
        var type = arguments[0];
        var bid = type + "-" + g.id;
        var bar = $("<div></div>").attr("id", bid);
        if (g.isBubble) {
            bar.addClass("ux-toolbar-bubble-" + type);
            if (type == "tbar") {
                g.dom.content.bwrap.before(bar);
            } else {
                g.dom.content.bwrap.after(bar);
            }
        } else {
            bar.addClass("ux-toolbar-" + type);
            if (type == "tbar") {
                g.dom.content.before(bar);
            } else {
                g.dom.content.after(bar);
            }
        }
        return EIAP.ToolBar({ renderTo: bid, items: g[type] });
    },
    setTitle: function () {
        if (arguments[0]) {
            this.dom.header.title.html(arguments[0]);
            this.dom.header.show();
        }
    },
    setWidth: function () {
        EIAP.panel.Panel.superclass.setWidth.call(this, arguments[0]);
        var w = this.dom.width();
        if (this.padding) {
            w -= 2 * this.padding;
        }
        if (this.isBubble) {
            w -= 12;
        }
        this.dom.content.width(w);
    },
    setHeight: function () {
        var g = this;
        var height = parseFloat(arguments[0]);
        if (height) {
            var parent = g.dom.parent();
            var pheight = parent.height();
            if (typeof arguments[0] == "string" && arguments[0].indexOf("%") > -1) {
                height /= 100;
                if (parent[0].tagName.toLowerCase() == "body") {
                    pheight = $(window).height();
                    pheight -= (parseFloat(parent.css("marginTop")) || 0);
                    pheight -= (parseFloat(parent.css("marginBottom")) || 0);
                    pheight -= (parseFloat(parent.css("paddingTop")) || 0);
                    pheight -= (parseFloat(parent.css("paddingBottom")) || 0);
                } else {
                    var parentCmp = EIAP.getCmp(g.parentCmp);
                    if (parentCmp == undefined) {
                        parent.children().each(function () {
                            if (!$(this).hasClass(g.boxCss) && !$(this).hasClass(g.domCss) && $(this).is(":visible")) {
                                pheight -= $(this).outerHeight();
                            }
                        });
                    }
                }
                height *= pheight;
            }
            g.tbar && (height -= 26);
            g.bbar && (height -= 26);
            if (g.dom.header.css("display") == "block") {
                height -= 25;
            }
            height -= parseFloat(this.dom.css("marginTop")) || 0;
            height -= parseFloat(this.dom.css("marginBottom")) || 0;
            if (this.border) {
                height -= 2;
            }
            if (this.padding) {
                height -= 2 * this.padding;
            }
            g.dom.content.height(height);
            g.isOverFlow ? g.dom.content.css("overflow", "auto") : g.dom.content.css("overflow", "hidden");
            g.height = arguments[0];
        } else {
            g.dom.content.css("height", "auto");
        }
    },
    setBubble: function () {
        var g = this;
        var cls = arguments[0] || g.type.toLowerCase();
        var tarr = ["tl", "tr", "tc"];
        var marr = ["ml", "mr", "mc"];
        var barr = ["bl", "br"];
        var head = g.dom.header;
        var body = g.dom.content;
        var bottom = $('<div class="ux-' + cls + '-bc"></div>');
        if (g.bbar) {
            g.dom.content.bwrap.after(bottom);
        } else {
            g.dom.content.bwrap.append(bottom);
        }
        for (var i = 0; i < tarr.length; i++) {
            head = head.wrap('<div class="ux-' + cls + '-' + tarr[i] + '"></div>');
        }
        for (i = 0; i < marr.length; i++) {
            body = body.wrap('<div class="ux-' + cls + '-' + marr[i] + '"></div>');
        }
        for (i = 0; i < barr.length; i++) {
            bottom = bottom.wrap('<div class="ux-' + cls + '-' + barr[i] + '"></div>');
        }
        g.dom.footer = bottom.parent().parent();
        !g.footer && g.dom.footer.addClass("ux-" + cls + "-nofooter");
        g.dom.css("border-width", 0);
    },

    getDom: function () {
        return this.dom.content;
    }

});
﻿EIAP.GridPanel = function () {
    return new EIAP.grid.GridPanel(arguments[0]);
};

/**
* @fileOverview 封装jqGrid数据表格
* @author flyChan
*/

/**
* @class EIAP.grid.GridPanel
* @constructor
* @param {Object} cfg ：配置参数
* @return {Object} grid ： grid组件，其中grid为jqGrid实例
*/
EIAP.grid.GridPanel = EIAP.extend(EIAP.panel.Panel, {
    gridCss: "ux-grid",
    contentCss: "ux-panel-grid",
    padding: null,
    exportXls: false,
    showSearch: true,
    showRefresh: false,
    searchCols: null,
    searchText: null,
    searchParams: null,
    autoLoad: true,
    initComponent: function () {
        this.setTbar();
        EIAP.grid.GridPanel.superclass.initComponent.call(this);
        $("div.ui-jqgrid-sortable").live("mouseenter", function () {
            var text = $(this)[0].textContent;
            $(this).attr("title", text);
        });
    },
    __getType: function () {
        return 'GridPanel';
    },

    __idPrev: function () {
        return 'GridPanel';
    },

    _extMethods: function () {
        return EIAP.grid.GridPanel;
    },
    initPanelCfg: function () {
        EIAP.applyHave(this, this.gridCfg);
    },
    initGridCfg: function () {
        var grid = $("<table id='g_" + this.id + "'></table>");
        grid.addClass(this.gridCss);
        this.dom.content.append(grid);
        var cfg = this.gridCfg;
        cfg.width = this.dom.content.width();
        cfg.height = this.dom.content.height() - 48;
        /**
        * @description 初始化pager
        */
        if (cfg.hasPager != false) {
            cfg.hasPager = true;
            cfg.pager = cfg.pager || this.id + "_pager";
            grid.after("<div id='" + cfg.pager + "'></div>");
            cfg.pager = "#" + cfg.pager;

            /**
            * @description 初始化页显示数目
            */
            if (!cfg.rowList) {
                var rowNum = cfg.rowNum = cfg.rowNum ? cfg.rowNum : 15;
                var rowList = [rowNum, rowNum + 10, rowNum + 20, rowNum + 40, rowNum + 60, rowNum + 80];
                cfg.rowList = rowList;
            }
            cfg.height += 27;
        }
        /**
        * @description 初始化数据类型
        */
        if (cfg.loadonce == true) {
            cfg.datatype = "local";
        }
        var basecfg = {
            mtype: "post",
            pagerpos: "left",
            recordpos: "right",
            pgtext: EIAP.cmpText.pgtext,
            viewrecords: true,
            rownumbers: true,
            loadError: function (re) {
                if (re && re.responseText) {
                    var status = { StatusSign: 2, Message: re.responseText };
                    EIAP.ProcessStatus && EIAP.ProcessStatus({ status: status });
                }
            },
            datatype: "json"
        };
        cfg = EIAP.apply(basecfg, cfg);
        this.grid = grid.jqGrid(cfg);
        $('#gbox_' + grid.attr('id')).css('border-style', 'none');
        $(cfg.pager).addClass("ui-jqgrid-pagerbar");
        if (cfg.loadonce == true && this.autoLoad) {
            this.refreshGrid();
        }
    },

    _rendered: function () {
        EIAP.grid.GridPanel.superclass._rendered.call(this);
        this.initGridCfg();
        this.postDataParam = EIAP.apply({}, this.grid.getGridParam("postData"));
        $("#gbox_" + this.id).css("border-style", "none");
        this.dom.content.css("overflow", "hidden");
        this.onResize();
    },
    setTbar: function () {
        var g = this, r = false, tbar = g.tbar ? g.tbar : [];
        if (tbar.length > 0) {
            for (var i = 0; i < tbar.length; i++) {
                if (tbar[i] == "->") {
                    r = true;
                    break;
                }
            }
        }
        if (g.showRefresh) {
            tbar.push({
                xtype: "Button",
                title: EIAP.cmpText.refresh,
                iconCls: 'icon-refresh',
                handler: function () { g.quickSearch(); }
            });
        }
        if (g.exportXls) {
            tbar.push("-");
            tbar.push({
                xtype: "Button",
                title: EIAP.cmpText.exportXls,
                iconCls: 'icon-exportxls',
                handler: function () { g.exportToXls(); }
            });
        }
        if (g.showSearch) {
            !r && tbar.push('->');
            var id = "searchBox_" + g.id;
            var srh = {
                xtype: "SearchBox",
                id: id,
                onSearch: function () {
                    g.quickSearch();
                }
            };
            if (g.searchText)
                srh.displayText = g.searchText;
            tbar.push(srh);
        }
        g.tbar = tbar.length > 0 ? tbar : null;
    },
    quickSearch: function () {
        var g = this;
        var searchbox = EIAP.getCmp("searchBox_" + g.id);
        var v = searchbox.getValue();
        if (g.grid.jqGrid("getGridParam", "loadonce")) {
            g.localSearch(v);
        } else {
            var url = g.grid.jqGrid("getGridParam", "url");
            var params = g.grid.jqGrid("getGridParam", "postData");
            var datas = { Value: v };
            datas = EIAP.apply(params || {}, datas);
            if (g.searchParams) {
                datas = EIAP.apply(datas, g.searchParams);
            }
            g.grid.jqGrid("setGridParam", { page: 1, datatype: "json", url: url, postData: datas }).trigger("reloadGrid");
        }
    },
    localSearch: function (keyValue) {
        var g = this;
        var value = $.trim(keyValue).toLowerCase();
        var keyColum = g.searchCols || g.getGridCols().visibleCols.colsName;
        var gridData = g.grid.data("beforeFilterData");
        if (gridData == undefined) {
            gridData = g.grid.jqGrid("getGridParam", "data");
            g.grid.data("beforeFilterData", gridData);
        }
        if (value == "") {
            g.setDataInGrid(gridData);
            return;
        }
        else {
            if (gridData && gridData.length == 0)
                return;
            else {
                var results = [];
                for (var i = 0; gridData && i < gridData.length; i++) {
                    var item = gridData[i];
                    for (var k = 0; k < keyColum.length; k++) {
                        var colName = keyColum[k];
                        if (item[colName] != null) {
                            if (item[colName].toString().toLowerCase().indexOf(value) >= 0) {
                                results.push(item);
                                break;
                            }
                        }
                    }
                }
                g.setDataInGrid(results);
            }
        }
    },
    getGridCols: function () {
        var g = this, cols = { allCols: [], visibleCols: { colsName: [], colsLabel: [] } };
        var gcols = g.grid.getGridParam("colModel");
        var glabels = g.grid.getGridParam("colNames");
        for (var i = 0; i < gcols.length; i++) {
            var colProp = g.grid.getColProp(gcols[i].name);
            if (!colProp.hidden) {
                cols.visibleCols.colsName.push(gcols[i].name);
            }
            cols.allCols.push(gcols[i].name);
        }
        for (var m = 0; m < glabels.length; m++) {
            cols.visibleCols.colsLabel.push(glabels[m].label);
        }
        return cols;
    },
    exportToXls: function () {
        var g = this;
        var expColLabel = g.getGridCols().visibleCols.colsLabel;
        var expColName = g.getGridCols().visibleCols.colsName;
        var expData = [];
        var loadonce = g.grid.jqGrid('getGridParam', 'loadonce');
        var row = {};
        var rowItem;
        if (!loadonce) {
            var rowids = g.grid.getDataIDs();
            for (var i = 0; i < rowids.length; i++) {
                rowItem = g.grid.getRowData(rowids[i]);
                for (var n = 0; n < expColName.length; n++) {
                    row[expColName[n].name] = encodeURI(rowItem[expColName[n].name]);
                }
                expData.push(row);
            }
        } else {
            var tmpData = g.grid.jqGrid('getGridParam', 'data');
            for (var i = 0; i < tmpData.length; i++) {
                rowItem = tmpData[i];
                for (var m = 0; m < expColName.length; m++) {
                    row[expColName[m].name] = encodeURI(rowItem[expColName[m].name]);
                }
                expData.push(row);
            }
        }
        if (expData.length == 0) {
            EIAP.MsgAlert(g.dataExport,g.dataExportFailure, 'error');
            return false;
        } else {
            $('body').find("#exportform").remove();
            var expform = $("<form></form>").attr("id", "exportform").attr("action", "../ExportToExcel/").attr("method", "post");
            var colName = $("<input type='hidden'></input>").attr("id", "colName").attr("name", "colName").val(JSON.stringify(expColName));
            var colTitle = $("<input type='hidden'></input>").attr("id", "colTitle").attr("name", "colTitle").val(JSON.stringify(expColLabel));
            var id = $("<input type='hidden'></input>").attr("id", "expData").attr("name", "expdata").val(JSON.stringify(expData));
            expform.append(id).append(colName).append(colTitle);
            $('body').append(expform);
            var form = $('#exportform');
            form.submit();
        }
    },
    setDataInGrid: function (data) {
        var g = this;
        g.grid.jqGrid("clearGridData", true);
        g.grid.jqGrid("setGridParam", {
            datatype: "local",
            page: 1,
            data: data
        }).trigger("reloadGrid");
    },
    gridDataReload: function (data) {
        var g = this;
        var gridData = g.grid.data("beforeFilterData");
        if (gridData) {
            g.grid.removeData("beforeFilterData");
        }
        g.setDataInGrid(data);
    },
    refreshGrid: function () {
        var g = this, args = arguments, postData;
        if (args.length > 0 && EIAP.isJsonObj(args[0])) {
            postData = args[0];
        } else {
            postData = g.grid.jqGrid("getGridParam", "postData");
        }
        if (g.grid.jqGrid("getGridParam", "loadonce")) {
            var url = g.grid.jqGrid("getGridParam", "url");
            if (url) {
                $.post(url, postData, function (data) {
                    for (var i = 0; i < args.length; i++) {
                        if (args[i] instanceof Function) {
                            args[1].call(g, data);
                        }
                    }
                    g.grid.removeData("beforeFilterData");
                    g.grid.jqGrid('clearGridData', true);
                    g.grid.jqGrid("setGridParam", {
                        data: data,
                        page: 1
                    }).trigger("reloadGrid");
                });
            }
        } else {
            g.grid.jqGrid("setGridParam", {
                datatype: "json",
                page: 1,
                postData: postData
            }).trigger("reloadGrid");
        }
    },
    getRowData: function () {
        var g = this, args = arguments;
        if (args.length != 0) {
            return g.grid.getRowData(args[0]);
        }
        return null;
    },
    setSelectRowById: function () {
        var g = this, args = arguments;
        if (args.length != 0) {
            g.grid.resetSelection();
            g.grid.setSelection(args[0], true);
        }
    },
    getSelectRow: function () {
        var g = this;
        var rows;
        var muti = g.grid.jqGrid("getGridParam", "multiselect");
        if (muti) {
            rows = [];
            var rowIds = g.grid.jqGrid('getGridParam', 'selarrrow');
            for (var i = 0; i < rowIds.length; i++) {
                rows.push(g.getRowData(rowIds[i]));
            }
        } else {
            var rowId = g.grid.jqGrid('getGridParam', 'selrow');
            rows = g.getRowData(rowId);
        }
        return rows;
    },
    getGridData: function () {
        var g = this;
        var rows = [];
        if (g.grid.jqGrid("getGridParam", "loadonce")) {
            rows = g.grid.jqGrid("getGridParam", "data");
        } else {
            var ids = g.grid.getDataIDs();
            for (var i = 0; i < ids.length; i++) {
                rows.push(g.getRowData(ids[i]));
            }
        }
        return rows instanceof Array ? rows : [];
    },
    onResize: function () {
        EIAP.grid.GridPanel.superclass.onResize.call(this);
        var pwidth = this.dom.content.width();
        var pheight = this.dom.content.height() - 49;
        if (this.gridCfg.hasPager == false) {
            pheight += 27;
        }
        if (this.grid) {
            this.grid.jqGrid("setGridWidth", pwidth);
            this.grid.jqGrid("setGridHeight", pheight);
        }
        this.dom.content.css("overflow", "hidden");
    },
    setPostParams: function () {
        var grid = this.grid;
        var newParams = arguments[0];
        var postData = this.postDataParam;
        EIAP.applyIf(newParams, postData);
        return grid.each(function () {
            if (this.grid && typeof newParams === 'object') {
                this.p.postData = newParams;
            }
        });
    },
    resetParam: function () {
        this.setPostParams(this.postDataParam);
    }
});﻿EIAP.Window = function () {
    return new EIAP.window.Window(arguments[0]);
};
EIAP.Window.show = function (p) {
    return EIAP.Window(p);
};
EIAP.window.Window = EIAP.extend(EIAP.panel.Panel, {
    isStatic: true,
    title: 'window',
    width: 320,
    height: 260,
    padding: 0,
    shadow: true,
    showClose: true,
    showMax: false,
    showToggle: false,
    showMin: false,
    modal: true,
    isBubble: true,
    resizeable: false,
    draggable: true,
    autoHeight: false,
    autoShow: true,
    closeAction: 'close',
    afterClose: null,
    beforeClose: null,
    boxCss: "ux-window ux-window-plain",
    contentCss: "ux-window-content",
    hearderCss: "ux-window-header",
    buttons: null,
    buttonAlign: 'right',
    initComponent: function () {
        if (this.buttons && this.buttons instanceof Array)
            this.footer = true;
        delete this.tbar;
        delete this.bbar;
        EIAP.window.Window.superclass.initComponent.call(this);
    },
    __getType: function () {
        return 'Window';
    },
    __idPrev: function () {
        return 'Window';
    },
    _extMethods: function () {
        return EIAP.window.Window;
    },
    _render: function () {
        var g = this;
        g.renderType = "window";
        EIAP.window.Window.superclass._render.call(this, g.renderType);
        g.element = g.dom[0];
        $('body').append(g.dom);
        //位置初始化
        var left = 0;
        var top = 0;
        if (g.left) left = g.left;
        else g.left = left = 0.5 * ($(window).width() - g.dom.width());
        if (g.top) top = g.top;
        else g.top = top = 0.5 * ($(window).height() - g.dom.height()) + $(window).scrollTop() - 60;
        if (left < 0) g.left = left = 0;
        if (top < 0) g.top = top = 0;
        g.dom.css({ left: g.left, top: g.top });
        g.initToolBox();
        g.initButtons();
        g._saveStatus();
        g.showShadow();
        g.addEvents();
        g.setShowMin(g.showMin);
        if (!g.autoShow) {
            g.hide();
        } else {
            g.mask(g);
            g.setActive();
        }
    },
    initToolBox: function () {
        var g = this;
        if (g.showToggle) g.dom.header.toolbox.append('<div class="ux-window-tools ux-window-toggle"></div>');
        if (g.showMax) g.dom.header.toolbox.append('<div class="ux-window-tools ux-window-max"></div>');
        if (g.showClose) g.dom.header.toolbox.append('<div class="ux-window-tools ux-window-close"></div>');
    },
    initButtons: function () {
        var g = this;
        if (g.footer) {
            g.buttonbox = $('<div class="ux-window-buttons"><div class="ux-window-buttons-inner"></div></div>');
            var w = 0;
            for (var i = 0; i < g.buttons.length; i++) {
                var btncfg = g.buttons[i];
                var btn = EIAP.Button(btncfg);
                g.items.push(btn.id);
                if (btncfg.width) {
                    w = w + btncfg.width + 10;
                    btn.dom.width(btncfg.width);
                } else {
                    btn.dom.width(75);
                    w += 85;
                }
                if (btncfg.iconCls) {
                    w += 24;
                }
                $('.ux-window-buttons-inner', g.buttonbox).append(btn.dom);
            }
            w = w >= g.width ? g.width : w;
            g.buttonAlign == "center" && $('.ux-window-buttons-inner', g.buttonbox).width(w);
            g.buttonbox.addClass("ux-window-footer").addClass("ux-window-buttons-" + g.buttonAlign);
            $('.ux-window-bc', g.dom.footer).append(g.buttonbox);
        }
    },
    showShadow: function () {
        var g = this;
        if (g.shadow && EIAP.Shadow) {
            g.dom.shadow = new EIAP.Shadow({ target: g.dom });
            g.items.push(g.dom.shadow.id);
            g.dom.shadow.updateShadow(g.dom);
        }
    },
    addEvents: function () {
        //设置事件 
        var g = this;
        $(".ux-window-toggle", g.dom).click(function () {
            if ($(this).hasClass("ux-window-toggle-close")) {
                g.collapsed = false;
                $(this).removeClass("ux-window-toggle-close ux-window-toggle-close-over");
            } else {
                g.collapsed = true;
                $(this).addClass("ux-window-toggle-close");
            }
            g.dom.shadow.hide();
            g.dom.content.slideToggle(function () {
                g.shadow && g.dom.shadow.updateShadow(g.dom);
            });
        }).hover(function () {
            if (g.dom.drag)
                g.dom.drag.set('disabled', true);
            if ($(this).hasClass("ux-window-toggle-close")) {
                $(this).addClass("ux-window-toggle-close-over");
            } else {
                $(this).addClass("ux-window-toggle-over");
            }
        }, function () {
            if (g.dom.drag)
                g.dom.drag.set('disabled', false);
            if ($(this).hasClass("ux-window-toggle-close")) {
                $(this).removeClass("ux-window-toggle-close-over");
            } else {
                $(this).removeClass("ux-window-toggle-over");
            }
        });
        $(".ux-window-close", g.dom).click(function () {
            if (g.trigger('close') == false) return false;
            if (g.closeAction == "hide") {
                g.hide();
            } else {
                g.close();
            }
        }).hover(function () {
            if (g.dom.drag)
                g.dom.drag.set('disabled', true);
            $(this).addClass("ux-window-close-over");
        }, function () {
            if (g.dom.drag)
                g.dom.drag.set('disabled', false);
            $(this).removeClass("ux-window-close-over");
        });
        $(".ux-window-max", g.dom).click(function () {
            if ($(this).hasClass("ux-window-regain")) {
                g.dom.css({ left: g.left, top: g.top });
                g.setWidth(g.width);
                g.setHeight(g.height);
                $(this).removeClass("ux-window-regain ux-window-regain-over");
                g.ismax = false;
            }
            else {
                g.ismax = true;
                g.max();
            }
            g.onResizeChildren();
            g.shadow && g.dom.shadow.updateShadow(g.dom);
        }).hover(function () {
            if ($(this).hasClass("ux-window-regain")) {
                $(this).addClass("ux-window-regain-over");
            } else {
                $(this).addClass("ux-window-max-over");
            }
        }, function () {
            if ($(this).hasClass("ux-window-regain")) {
                $(this).removeClass("ux-window-regain-over");
            } else {
                $(this).removeClass("ux-window-max-over");
            }
        });
        $(".ux-header-inner", g.dom).hover(function () {
            if (g.dom.drag) {
                g.ismax == true ? g.dom.drag.set('disabled', true) : g.dom.drag.set('disabled', false);
            }
        }, function () {

        });
        g.dom.click(function () {
            g.setActive();
        });
        //拖动支持
        if (EIAP.Drag && g.draggable) {
            g.dom.drag = new EIAP.Drag({
                target: g.dom,
                proxy: true,
                dragHandler: '.ux-header-inner',
                onStartDrag: function () {
                    $(document).trigger("click");
                    g.setActive();
                    if (g.dom.shadow) g.dom.shadow.hide();
                    g.dom.hide();
                },
                onStopDrag: function () {
                    g._saveStatus();
                    g.show();
                },
                animate: false
            });
        }
        //改变大小支持
        if (EIAP.Resizable && g.resizeable) {
            g.dom.resizable = new EIAP.Resizable({
                target: g.dom,
                onStartResize: function () {
                    g.setActive();
                    if (g.dom.shadow) g.dom.shadow.hide();
                },
                onStopResize: function (current, e) {
                    if (!isNaN(parseInt(g.dom.css('top'))))
                        top = parseInt(g.dom.css('top'));
                    if (!isNaN(parseInt(g.dom.css('left'))))
                        left = parseInt(g.dom.css('left'));
                    if (current.diffTop)
                        g.dom.css({ top: top + current.diffTop });
                    if (current.diffLeft)
                        g.dom.css({ left: left + current.diffLeft });
                    if (current.newWidth) {
                        g.width = current.newWidth;
                        g.setWidth(current.newWidth);
                    }
                    if (current.newHeight) {
                        g.height = current.newHeight;
                        g.setHeight(current.newHeight);
                    }
                    g.onResizeChildren();
                    g.setActive();
                    g._saveStatus();
                    return false;
                }
            });
            g.dom.append("<div class='ux-btn-nw-drop'></div>");
            g.items.push(g.dom.resizable.id);
        }
    },
    _saveStatus: function () {
        var g = this;
        var top = 0, left = 0;
        if (!isNaN(parseInt(g.dom.css('top'))))
            top = parseInt(g.dom.css('top'));
        if (!isNaN(parseInt(g.dom.css('left'))))
            left = parseInt(g.dom.css('left'));
        g.top = top;
        g.left = left;
    },
    min: function () {
        this.dom.hide();
        this.minimize = true;
        this.actived = false;
    },
    max: function () {
        var g = this, w = $(window).width(), h = $(window).height();
        g.dom.css({ left: 4, top: 4 });
        g.setWidth(w - 8);
        g.footer ? h -= 74 : h -= 42;
        g.setHeight(h);
        $(".ux-window-max", g.dom).addClass("ux-window-regain");
    },
    setShowMin: function (v) {
        var g = this;
        if (v) {
            if (!g.winmin) {
                g.winmin = $('<div class="ux-window-tools ux-window-min"></div>').prependTo(g.dom.header.toolbox)
                    .click(function () {
                        g.min();
                    }).hover(function () {
                        $(this).addClass("ux-window-min-over");
                    }, function () {
                        $(this).removeClass("ux-window-min-over");
                    });
            }
        }
        else if (g.winmin) {
            g.winmin.remove();
            g.winmin = null;
        }
    },
    setLeft: function (v) {
        if (v != null)
            this.dom.css({ left: v });
    },
    setTop: function (v) {
        if (v != null)
            this.dom.css({ top: v });
    },
    setWidth: function (v) {
        if (v > 0) {
            this.dom.width(v);
            v -= 2 * this.padding;
            this.dom.content.width(v - 14);
            this.dom.shadow && this.dom.shadow.updateShadow(this.dom);
        }
    },
    setHeight: function (v) {
        if (this.autoHeight) {
            this.dom.content.width(this.width - 12);
        } else {
            v -= 2 * this.padding;
            this.dom.content.height(v);
            this.dom.shadow && this.dom.shadow.updateShadow(this.dom);
        }
    },
    setTitle: function (v) {
        if (v)
            $(".ux-header-inner", this.dom.header).html(v);
    },
    hide: function () {
        this.unmask(this);
        this.dom.hide();
        if (this.dom.shadow) this.dom.shadow.hide();
        this.setLastActive();
    },
    show: function () {
        var g = this;
        g.mask(this);
        g.dom.animate({ left: g.ismax ? 4 : g.left, top: g.ismax ? 4 : g.top, opacity: 'show' }, 200, function () {
            g.setFront(g);
            g.shadow && g.dom.shadow.updateShadow(g.dom);
        });
    },
    close: function () {
        if (this.beforeClose) {
            if (this.beforeClose() == false) {
                return;
            }
        }
        this.unmask(this);
        EIAP.remove(this);
        this.setLastActive();
        EIAP.wmanagers.splice(this.index, 1);
        this.afterClose && this.afterClose();
    },

    setLastActive: function () {
        var wins = EIAP.wmanagers;
        var idx = this.index - 1;
        if (idx >= 0) {
            var nextWin = wins[idx];
            nextWin.actived = true;
            var upindex = 9200;
            if (nextWin.dom.is(":visible")) {
                nextWin.modal && nextWin.windowMask.css('z-index', upindex - 10);
                nextWin.dom.css('z-index', upindex);
                nextWin.shadow && nextWin.dom.shadow.updateShadow(nextWin.dom);
                nextWin.dom.header.removeClass("ux-window-blur");
            }
        }
    },

    setActive: function () {
        var g = this;
        if (g.minimize) {
            var width = g.width, height = g.height, left = g.left, top = g.top;
            if (g.maximum) {
                width = $(window).width();
                height = $(window).height();
                left = top = 0;
            }
            g.set({ width: width, height: height, left: left, top: top });
        }
        g.actived = true;
        g.minimize = false;
        g.show();
    },
    //遮罩
    mask: function (win) {
        if (win.modal) {
            var setHeight = function () {
                if (!EIAP.Window.windowMask) return;
                var h = $(window).height() + $(window).scrollTop();
                EIAP.Window.windowMask.height(h);
            };
            if (!this.windowMask) {
                this.windowMask = $("<div class='ux-window-mask' style='display: block;'></div>").appendTo('body');
                $(window).bind('resize.eiapuiwin', setHeight);
                $(window).bind('scroll', setHeight);
            }
            this.windowMask.show();
            setHeight();
            this.masking = true;
        }
    },

    //取消遮罩
    unmask: function () {
        if (this.modal) {
            var jwins = $("body > .ux-dialog:visible,body > .ux-window:visible");
            for (var i = 0, l = jwins.length; i < l; i++) {
                var winid = jwins.eq(i).attr("eiapuiid");
                if (this.id == winid) continue;
                //获取ui对象
                var winmanager = EIAP.get(winid);
                if (!winmanager) continue;
            }
            if (this.windowMask) {
                this.closeAction == "close" ? this.windowMask.remove() : this.windowMask.hide();
            }
            this.masking = false;
        }
    },

    //前端显示
    setFront: function (win) {
        var wins = EIAP.wmanagers;
        var upindex = 9200, downindex = 9000;
        for (var i = wins.length - 1; i >= 0; i--) {
            var w = wins[i];
            if (w.dom.is(":visible")) {
                if (w.id == win.id) {
                    w.modal && w.windowMask.css('z-index', upindex - 10);
                    w.dom.css('z-index', upindex);
                    w.shadow && w.dom.shadow.updateShadow(w.dom);
                    w.dom.header.removeClass("ux-window-blur");
                } else {
                    EIAP.managers[w.id].actived = false;
                    w.dom.css('z-index', --downindex);
                    w.shadow && w.dom.shadow.dom.hide();
                    w.modal && w.windowMask.css('z-index', --downindex);
                    w.dom.header.addClass("ux-window-blur");
                }
            }
        }
    },

    addItems: function () {
        var items = this.options.items;
        if (this.html || (items != undefined && items.length > 1)) {
            EIAP.panel.Panel.superclass.addItems.call(this);
        } else if (items && items.length == 1) {
            var item = items[0];
            var xtype = item.xtype ? item.xtype : this.defaultType;
            if (!xtype) {
                throw new Error(EIAP.error.noXtype);
            }
            EIAP.applyIf(item, this.defaultStyle);
            var id = item.id ? item.id : EIAP.getId(xtype);
            this.getDom().append("<div id='" + id + "'></div>");
            item.renderTo = id;
            var cmp = eval("EIAP." + xtype);
            if (!cmp) {
                throw new Error(String.format(EIAP.error.noCmp, xtype));
            }
            var p = cmp.call(cmp, item);
            this.items.push(p.id);
        }
    },
    onResizeChildren: function () {
        var g = this;
        for (var i = 0; i < g.items.length; i++) {
            EIAP.resize(EIAP.getCmp(g.items[i]));
        }
    },
    onResize: function () {
        var g = this;
        g.ismax && g.max();
        g.shadow && g.dom.shadow.updateShadow(g.dom);
        g.onResizeChildren();
    }
});﻿EIAP.FormPanel = function () {
    return new EIAP.panel.FormPanel(arguments[0]);
};

EIAP.panel.FormPanel = EIAP.extend(EIAP.panel.Panel, {
    url: null,
    store: null,
    afterLoad: null,
    layout: "form",
    formCss: "ux-form",
    initComponent: function () {
        EIAP.panel.FormPanel.superclass.initComponent.call(this);
        if (this.store) {
            this.beforeLoad && this.on('beforeLoad', this.beforeLoad);
            this.afterLoad && this.on('afterLoad', this.afterLoad);
            this.initStore();
        }
    },
    __getType: function () {
        return 'FormPanel';
    },
    __idPrev: function () {
        return 'FormPanel';
    },
    _extMethods: function () {
        return EIAP.panel.FormPanel;
    },

    submit: function () {
        if (this.isValid()) {
            var config = arguments[0] || {};
            var data = this.getFormValue();
            EIAP.applyIf(config, { params: data });
            EIAP.applyIf(config, { url: this.url });
            config.autoLoad = true;
            EIAP.Store(config);
        }
    },
    isValid: function () {
        return this.doValidate(this.items);
    },
    doValidate: function () {
        var items = arguments[0];
        var flag = true;
        if (items) {
            for (var i = 0; i < items.length; i++) {
                var item = EIAP.getCmp(items[i]);
                if (item.isDefined) {
                    if (item.isFormField || item.needValid) {
                        var tmp = item.sysValidater();
                        flag = flag && tmp;
                    } else {
                        flag = this.doValidate(item.items) && flag;
                    }
                }
            }
        }
        return flag;
    },

    getFormValue: function () {
        var items = this.items;
        var data = {};
        for (var i = 0; i < items.length; i++) {
            var item = EIAP.getCmp(items[i]);
            if (item.isDefined) {
                EIAP.applyIf(data, this.getItemValue(item));
            }
        }
        return data;
    },

    getItemValue: function () {
        var item = arguments[0];
        var data = {};
        if (item.isFormField) {
            EIAP.applyIf(data, item.getSubmitValue());
        }
        if (item.items) {
            for (var i = 0; i < item.items.length; i++) {
                EIAP.applyIf(data, this.getItemValue(EIAP.getCmp(item.items[i])));
            }
        }
        return data;
    },

    reset: function () {
        this.doReset(this.items);
    },

    doReset: function () {
        var items = arguments[0];
        if (items) {
            for (var i = 0; i < items.length; i++) {
                var item = EIAP.getCmp(items[i]);
                if (item.isDefined) {
                    if (item.isFormField) {
                        item.reset();
                    }
                    this.doReset(item.items);
                }
            }
        }
    },

    loadData: function () {
        if (arguments[0]) {
            this.data = arguments[0];
        }
        this.doLoadData(this.items);
        this.isValid();
    },
    doLoadData: function () {
        var items = arguments[0];
        if (items) {
            for (var i = 0; i < items.length; i++) {
                var item = EIAP.getCmp(items[i]);
                if (item.isDefined) {
                    if (item.isFormField) {
                        item.loadData(this.data);
                    }
                    this.doLoadData(item.items);
                }
            }
        }
    },
    initStore: function () {
        var g = this;
        g.store.success = function (response) {
            g.data = response.data;
            g.loadData();
            g.fireEvent('afterLoad', g.data);
        };
        g.store.autoLoad = true;
        g.fireEvent('beforeLoad', g);
        var store = EIAP.Store(g.store);
        g.store = store;
    },

    getCmpByName: function () {
        var name = arguments[0];
        var items = this.items;
        return this.doGetCmp(items, name);
    },

    doGetCmp: function () {
        var items = arguments[0], name = arguments[1];
        if (items) {
            for (var i = 0; i < items.length; i++) {
                var item = EIAP.getCmp(items[i]);
                if (item.isDefined) {
                    if (item.isFormField && item.name == name) {
                        return item;
                    } else {
                        var cmp = this.doGetCmp(item.items, name);
                        if (cmp != null) {
                            return cmp;
                        }
                    }
                }
            }
        }
        return null;
    }

});﻿EIAP.TreePanel = function () {
    return new EIAP.panel.TreePanel(arguments[0]);
};
EIAP.panel.TreePanel = EIAP.extend(EIAP.panel.Panel, {
    initComponent: function () {
        EIAP.panel.TreePanel.superclass.initComponent.call(this);
    },
    __getType: function () {
        return 'TreePanel';
    },
    __idPrev: function () {
        return 'TreePanel';
    },
    _extMethods: function () {
        return EIAP.panel.TreePanel;
    },
    _render: function () {
        var g = this;
        EIAP.panel.TreePanel.superclass._render.call(this);
        var cfg = g.options;
        var renderTo = cfg.renderTo;
        delete cfg.renderTo;
        cfg.id && delete cfg.id;
        var tree = EIAP.Tree(cfg);
//        tree.parentCmp = g.id;
//        g.items.push(tree.id);
        g.tree = tree;
        g.dom.content.append(tree.dom);
        cfg.renderTo = renderTo;
        g.setWidth(g.width);
    },
    setWidth: function () {
        EIAP.panel.TreePanel.superclass.setWidth.call(this, arguments[0]);
        this.tree && this.tree.dom.width(this.dom.content.width() - 17);
    }
});﻿EIAP.TabPanel = function () {
    return new EIAP.panel.TabPanel(arguments[0]);
};
EIAP.panel.TabPanel = EIAP.extend(EIAP.panel.Panel, {
    minWidth: 80,
    maxWidth: 200,
    maxTabs: 20,
    padding: 0,
    border: true,
    tabWidth: null,
    showTabMenu: false,
    overflowText: null,
    autoScroll: true,
    tabCss: "ux-tab",
    leftCss: "ux-tab-scrollLeft",
    rightCss: "ux-tab-scrollRight",
    itemLeftCss: "ux-tab-item-left",
    itemRightCss: "ux-tab-item-right",
    itemCloseCss: "ux-tab-item-close",
    ulCss: "ux-tab-ul",
    liCss: "ux-tab-li",
    aCss: "ux-tab-li-a",
    iconCss: "ux-tab-icon",
    headerCss: "ux-tab-header",
    contentCss: "ux-tab-content",
    activeCss: "ux-tab-actived",
    wrapCss: "ux-tab-wrap",
    disableLeft: "ux-tab-scrollLeft-disable",
    disableRight: "ux-tab-scrollRight-disable   ",
    onActive: null,
    beforeClose: null,
    afterClose: null,

    initComponent: function () {
        EIAP.panel.TabPanel.superclass.initComponent.call(this);
        if (this.onActive) {
            this.on('onActive', this.onActive);
        }
        if (this.beforeClose) {
            this.on('beforeClose', this.beforeClose);
        }
        if (this.afterClose) {
            this.on('afterClose', this.afterClose);
        }
        this.totalWidth = 0;
    },
    __getType: function () {
        return 'TabPanel';
    },
    __idPrev: function () {
        return 'TabPanel';
    },
    _extMethods: function () {
        return EIAP.panel.TabPanel;
    },
    _render: function () {
        EIAP.panel.TabPanel.superclass._render.call(this);
        this.tab = this.dom.content;
        this.initCmp();
        this.addEvents();
        this.setTabHeight();
    },
    initCmp: function () {
        var g = this;
        var header = $("<div></div>").addClass(g.headerCss);
        var left = $("<div class='" + g.leftCss + "'></div>").hide();
        var right = $("<div class='" + g.rightCss + "'></div>").hide();
        var ul = $("<ul class='" + g.ulCss + "'></ul>").width(6000);
        var wrap = $("<div class='" + g.wrapCss + "'></div>");
        wrap.append(ul);
        header.append(left).append(wrap).append(right);
        header.left = left;
        header.right = right;
        header.ul = ul;
        header.wrap = wrap;
        var content = $("<div class='" + g.contentCss + "'></div>");
        g.tab.append(header).append(content);
        g.tab.header = header;
        g.tab.content = content;
        g.wrapWidth = wrap.width();
    },
    addEvents: function () {
        var g = this;
        //右移按钮事件
        g.tab.header.right.bind("click", function () {
            if ($(this).hasClass(g.disableRight)) {
                return;
            }
            var last = $("li:last", g.tab.header.ul);
            var lastLeft = last.offset().left;
            var rightBtn = g.tab.header.right.offset().left;
            if (lastLeft + last.width() > rightBtn) {
                var ul = g.tab.header.ul;
                var ulLeft = ul.offset().left;
                var scrollWidth = g.tabWidth ? g.tabWidth : 120;
                scrollWidth = ulLeft - scrollWidth - g.tab.header.offset().left;
                if (lastLeft <= rightBtn) {
                    scrollWidth = ul.position().left - (last.width() + lastLeft - rightBtn) - 2;
                }
                ul.animate({ left: scrollWidth }, function () {
                    if (last.offset().left + last.width() + 2 <= rightBtn) {
                        g.tab.header.right.addClass(g.disableRight);
                    }
                });
            }
            g.tab.header.left.removeClass(g.disableLeft);
        });
        //左移按钮事件
        g.tab.header.left.bind("click", function () {
            if ($(this).hasClass(g.disableLeft)) {
                return;
            }
            var first = $("li:first", g.tab.header.ul);
            var firstLeft = first.offset().left;
            var leftBtn = g.tab.header.left.offset().left;
            var leftWidth = g.tab.header.left.width();
            if (firstLeft < leftBtn + leftWidth + 2) {
                var ul = g.tab.header.ul;
                var scrollWidth = g.tabWidth ? g.tabWidth : 120;
                scrollWidth += ul.position().left;
                if (firstLeft + first.width() > leftBtn + leftWidth + 2) {
                    scrollWidth = leftWidth;
                }
                //设置绝对位移
                ul.animate({ left: scrollWidth }, function () {
                    if (first.offset().left >= leftBtn + leftWidth + 2) {
                        g.tab.header.left.addClass(g.disableLeft);
                    }
                });
            }
            g.tab.header.right.removeClass(g.disableRight);
        });
        if (g.showTabMenu) {
            $("." + g.liCss, g.dom).live("contextmenu", function (e) {
                var index = $("." + g.liCss).index(this);
                if (g.menu) {
                    EIAP.remove(g.menu);
                }
                var items = [];
                var item = g.options.items[index];
                if (g.activedIndex == index && item.iframe) {
                    items = [{
                        title: g.tRefresh,
                        iconCls: 'icon-common-refresh',
                        handler: function () {
                            g.refresh(index);
                        }
                    }, "-"];
                }
                if (g.options.items[index].closable) {
                    items.push({
                        title: g.tClose,
                        iconCls: 'icon-info-mail_remove',
                        handler: function () {
                            g.close(index);
                        }
                    });
                }
                items.push({
                    title: g.tCloseOthers,
                    handler: function () {
                        g.closeOther(index);
                    }
                });
                items.push({
                    title: g.tCloseAll,
                    handler: function () {
                        g.closeAll();
                    }
                });
                g.menu = EIAP.Menu({
                    width: 100,
                    items: items
                });
                g.menu.show({ top: e.pageY, left: e.pageX });
                return false;
            });
        }
    },
    setTabHeight: function () {
        var heigth = this.tab.height() - 27;
        if (this.border) {
            heigth -= 2;
        }
        this.isOverFlow ? this.tab.content.css("overflow", "auto") : this.tab.content.css("overflow", "hidden");
        if (this.height == 0) {
            this.tab.content.css("height", "auto");
        } else if (heigth > 0) {
            this.tab.content.height(heigth);
        }
    },
    setTitle: function (index, title) {
        var li = $("li:eq(" + index + ")", this.tab.header.ul);
        $(".ux-tab-inner span", li).html(title);
    },
    addItems: function () {
        var g = this, items = g.options.items;
        var activeIndex = 0;
        if (items) {
            if (g.maxTabs && items.length > g.maxTabs) {
                throw new Error(String.format(g.initTooMuch, items.length, g.maxTabs));
            }
            for (var i = 0; i < items.length; i++) {
                var item = items[i];
                if (item.actived) {
                    activeIndex = i;
                }
                item.actived = false;
                var fn = g.initItem(item);
                g.doAddTitle(item);
                g.doAddContent(fn, item);

            }
            g.activedIndex = activeIndex;
            g.active(activeIndex);
        }
    },
    initItem: function () {
        var item = arguments[0], g = this;
        EIAP.applyIf(item, g.defaultStyle);
        var defaultConf = { closable: false, async: true, iframe: false };
        EIAP.applyIf(item, defaultConf);
        if (!item.iframe) {
            var xtype = item.xtype ? item.xtype : g.defaultType;
            if (!xtype) {
                throw new Error(EIAP.error.noXtype);
            }
            var fn = eval("EIAP." + xtype);
            if (!fn) {
                throw new Error(String.format(EIAP.error.noCmp, xtype));
            }
            return fn;
        } else {
            return null;
        }
    },
    doAddTitle: function () {
        var g = this, item = arguments[0];
        var title = item.title ? item.title : "";
        delete item.title;
        var li = $("<li></li>").addClass(g.liCss);
        li.bind("click", function () {
            var index = g.dom.find("." + g.liCss).index(this);
            g.active(index);
        });
        var a = $("<a></a>").addClass(g.aCss);
        if (item.iconCls)
            a.append("<span class='" + g.iconCss + " " + item.iconCls + "'></span>&nbsp;");
        var inner = $("<span class='ux-tab-inner'></span>");
        var titleDiv = $("<span>" + title + "</span>");
        inner.append(titleDiv);
        a.append(inner);
        li.append(a);
        li.append("<div class='" + g.itemLeftCss + "'></div>");
        li.append("<div class='" + g.itemRightCss + "'></div>");
        //关闭事件
        if (item.closable) {
            var close = $("<div class='" + g.itemCloseCss + "'></div>");
            close.bind("click", function () {
                var index = $("li", g.tab.header.ul).index(close.parent());
                g.close(index);
                return false;
            });
            li.append(close);
        }
        g.tab.header.ul.append(li);
        //title宽度
        if (g.tabWidth) {
            inner.width(g.tabWidth);
        } else {
            var tw = titleDiv.width();
            if (tw > g.maxWidth) {
                inner.width(g.maxWidth);
            }
            if (tw < g.minWidth) {
                inner.width(g.minWidth);
            }
        }
        delete item.iconCls;
        var wrap = g.tab.header.wrap;
        //记录所有tab标题的长度
        g.totalWidth += (2 + li.width());
        if (g.autoScroll && !g.scrolled && wrap.width() < g.totalWidth) {
            g.tab.header.left.show();
            g.tab.header.right.show();
            g.tab.header.ul.animate({ left: g.tab.header.left.width() }, function () {
                g.tab.header.right.removeClass(g.disableRight);
            });
            g.scrolled = true;
        }
    },
    doAddContent: function () {
        var g = this, item = arguments[1], id, fn = arguments[0];
        if (!item.iframe) {
            id = item.id ? item.id : EIAP.getId(item.xtype);
            var div = $("<div id='" + id + "'></div>");
            g.tab.content.append(div);
            item.renderTo = id;
            if (!item.async) {
                var cmp = fn.call(fn, item);
                g.items.push(cmp.id);
            }
            div.hide();
        } else {
            if (!item.url) {
                throw new Error(EIAP.error.noUrl);
            }
            var iframe = $('<iframe frameborder="0" width="100%" height="100%"></iframe>').attr("src", item.url);
            iframe.bind("load", function () {
                g.mask && g.mask.hide();
            });
            id = item.id ? item.id : EIAP.getId("iframe");
            item.renderTo = id;
            iframe.attr("id", item.renderTo);
            g.tab.content.append(iframe);
            iframe.hide();
        }
    },
    addTab: function () {
        var g = this, item = arguments[0];
        if (item.id) {
            for (var i = 0; i < g.options.items.length; i++) {
                if (g.options.items[i].renderTo == item.id) {
                    g.active(item.id);
                    return null;
                }
            }
        }
        if (g.maxTabs && g.options.items.length >= g.maxTabs) {
            EIAP.Msg.show({
                title: g.tTips,
                msg: String.format(g.overflowText, g.maxTabs),
                buttons: EIAP.Msg.OK,
                iconCls: 'icon-app',
                icon: EIAP.Msg.WARNING
            });
            return null;
        } else if (!g.maxTabs && g.totalWidth + 200 > g.tab.header.wrap.width()) {
            EIAP.Msg.show({
                title: g.tTips,
                msg: String.format(g.tOpenItems, g.options.items.length),
                buttons: EIAP.Msg.OK,
                iconCls: 'icon-app',
                icon: EIAP.Msg.WARNING
            });
            return null;
        }
        if (item.iframe) {
            var mask = EIAP.LoadMask(g);
            mask.show();
            g.mask = mask;
        }
        item.parentCmp = g.id || g.renderTo;
        item.isDefined = true;
        var fn = g.initItem(item);
        g.doAddTitle(item);
        g.doAddContent(fn, item);
        g.options.items.push(item);
        return this;
    },
    show: function () {
        var index = $("li", this.tab.header.ul).length;
        this.active(index - 1);
    },
    getTab: function () {
        var g = this, index, id;
        if (typeof arguments[0] == "number") {
            index = arguments[0];
            var divs = g.tab.content.children();
            if (index > divs.length - 1) {
                return null;
            }
            id = $(divs[index]).attr("id");
        } else {
            id = arguments[0];
        }
        return EIAP.getCmp(id);
    },
    getActiveTab: function () {
        var g = this, recmp = null;
        for (var i = 0; i < g.items.length; i++) {
            var cmp = EIAP.getCmp(g.items[i]);
            if (cmp && cmp.actived) {
                recmp = cmp;
                break;
            } else {
                continue;
            }
        }
        return recmp;
    },
    active: function () {
        var g = this, ul = g.tab.header.ul, index, id, cmp, lis = $("li", ul);
        var items = g.options.items;
        if (typeof arguments[0] == "number") {
            index = arguments[0];
            var divs = g.tab.content.children();
            if (index > divs.length - 1) {
                return;
            }
            id = $(divs[index]).attr("id");
        } else {
            id = arguments[0];
        }
        if (id == g.activedId) {
            return;
        } else if (g.activedId) {
            cmp = EIAP.getCmp(g.activedId);
            if (cmp) {
                cmp.actived = false;
            } else {
                items[g.activedIndex].actived = false;
            }
        }
        cmp = EIAP.getCmp(id);
        if (!index && index != 0) {
            for (var i in items) {
                if (items[i].renderTo == id) {
                    index = i;
                    break;
                }
            }
        }
        if (!cmp) {
            if (!items[index].iframe) {
                var xtype = items[index].xtype ? items[index].xtype : g.defaultType;
                var div = $("#" + items[index].renderTo);
                div.siblings().hide();
                div.show();
                var fn = eval("EIAP." + xtype);
                cmp = fn.call(fn, items[index]);
                g.items.push(cmp.id);
            }
        } else {
            if (cmp.actived) {
                return;
            }
        }
        var li = $(lis[index]).show();
        li.addClass(g.activeCss).siblings().removeClass(g.activeCss);
        if (items[index].iframe) {
            $(g.tab.content.children()[index]).show().siblings().hide();
            //设置激活标记
            items[index].actived = true;
        } else {
            cmp.dom.show().siblings().hide();
            //设置激活标记
            cmp.actived = true;
        }
        //记录激活的索引
        g.activedIndex = index;
        g.activedId = id;
        g.autoScroll && g.scrollVisible(index);
        //触发激活事件
        if (this.onActive) {
            this.fireEvent('onActive', index);
        }
    },
    scrollVisible: function (index) {
        var g = this, activedTab, leftBtn, rightBtn, lis, scrollWidth;
        if (g.scrolled) {
            lis = $("li", g.tab.header.ul);
            activedTab = $(lis[index]);
            var activeLeft = activedTab.offset().left;
            var ul = g.tab.header.ul;
            var ulLeft = ul.offset().left;
            leftBtn = g.tab.header.left.offset().left;
            rightBtn = g.tab.header.right.offset().left;
            var leftBtnWidth = g.tab.header.left.is(":visible") ? g.tab.header.left.width() : 0;
            //如果在左边被隐藏
            if (activeLeft < leftBtn + leftBtnWidth + 2) {
                scrollWidth = leftBtn + leftBtnWidth;
            } else if (activeLeft + activedTab.width() > rightBtn) {
                //如果在右边被隐藏
                scrollWidth = ulLeft - (activedTab.width() + activeLeft + 2 - rightBtn);
            }
            if (scrollWidth != undefined) {
                g.tab.header.ul.offset({ left: scrollWidth });
            }
            var firstLeft = $(lis[0]).offset().left;
            if (firstLeft - 2 >= leftBtn + leftBtnWidth) {
                g.tab.header.left.addClass(g.disableLeft);
            } else {
                g.tab.header.left.removeClass(g.disableLeft);
            }
            var last = $(lis[lis.length - 1]);
            var lastLeft = last.offset().left;
            if (lastLeft + last.width() + 2 <= rightBtn) {
                g.tab.header.right.addClass(g.disableRight);
            } else {
                g.tab.header.right.removeClass(g.disableRight);
            }
        }
    },
    onResize: function () {
        EIAP.panel.TabPanel.superclass.onResize.call(this);
        var g = this, ul = g.tab.header.ul, wrapWidth = g.tab.header.wrap.width() - 36;
        g.setTabHeight();
        if (g.autoScroll && wrapWidth != g.wrapWidth) {
            if (g.totalWidth > wrapWidth) {
                if (!g.scrolled) {
                    g.tab.header.left.show();
                    g.tab.header.right.show();
                    //                    ul.position({ left: 0 });
                    g.scrolled = true;
                }
                g.scrollVisible(g.activedIndex);
            } else {
                if (g.scrolled) {
                    g.tab.header.left.hide();
                    g.tab.header.right.hide();
                    ul.offset({ left: 3 });
                    //                    g.scrollVisible(0);
                    g.scrolled = false;
                }
            }
        }
        g.wrapWidth = g.tab.header.wrap.width();
        g.tab.content.width(g.wrapWidth);
        var tcmp = g.getTab(g.activedIndex);
        tcmp && tcmp.onResize();
    },
    close: function () {
        var g = this, ul = g.tab.header.ul, items = g.options.items, index, id;
        //找到当前页签的序号
        if (typeof arguments[0] == "number") {
            index = arguments[0];
            var divs = g.tab.content.children();
            id = $(divs[index]).attr("id");
        } else if (typeof arguments[0] == "string") {
            id = arguments[0];
            for (var i in items) {
                if (items[i].renderTo == id) {
                    index = i;
                    break;
                }
            }
        }
        //触发关闭前事件
        if (g.beforeClose) {
            var flag = g.fireEvent("beforeClose", index);
            if (flag == false)
                return;
        }
        var li = $(ul.children()[index]);
        var nowTabWidth = li.width();
        g.totalWidth -= li.width();
        //删除对应html元素
        li.remove();
        $(g.tab.content.children()[index]).remove();
        var isActived = items[index].actived;
        //删除options中item
        items.splice(index, 1);
        //删除组件items中item,组件管理器删除组件，删除所有子组件
        var cmp = EIAP.getCmp(id);
        if (cmp) {
            isActived = cmp.actived;
            var cmpItems = g.items;
            for (var j in cmpItems) {
                if (cmpItems[j] == id) {
                    cmpItems.splice(j, 1);
                    break;
                }
            }
            EIAP.remove(id);
        }
        //激活当前标签的下一个标签
        if (isActived) {
            g.activedId = null;
            g.activedIndex = null;
            if (index < items.length)
                g.active(index);
            else if (index > 0)
                g.active(index - 1);
        } else {
            if (index < g.activedIndex)
                g.activedIndex -= 1;
        }

        if (g.scrolled) {
            g.tab.header.ul.offset({ left: g.tab.header.ul.offset().left + nowTabWidth });
            var wrapWidth = g.tab.header.wrap.width() - g.tab.header.left.width() - g.tab.header.right.width();
            //判断是否需要左右移动按钮
            if (wrapWidth >= g.totalWidth) {
                g.tab.header.left.hide();
                g.tab.header.right.hide();
                //将第一个Tab页签移动到最左边

                g.tab.header.wrap.animate({ left: 0 }, function () {
                    g.tab.header.ul.offset({ left: g.tab.header.offset().left });
                });
                g.scrolled = false;
            }
        }

        //关闭后事件
        if (g.afterClose) {
            g.fireEvent("afterClose", index);
            if (!flag)
                return;
        }
    },
    closeOther: function (index) {
        var g = this;
        var lis = $("." + g.liCss, g.tab.header.ul);
        var isActived = false, activedTab = $(lis[g.activedIndex]);
        for (var i = lis.length - 1; i >= 0 ; i--) {
            if (i != index && g.options.items[i].closable) {
                g.doClose(i, $(lis[i]));
            }
            else if (!isActived) {
                isActived = (i == g.activedIndex);
            }
        }
        if (!isActived) {
            g.activedId = null;
            g.activedIndex = null;
            g.active(0);
        } else {
            g.activedIndex = g.dom.find("." + g.liCss).index(activedTab);
        }
    },
    closeAll: function () {
        var g = this;
        var lis = $("." + g.liCss, g.tab.header.ul);
        var isActived = false, activedTab = $(lis[g.activedIndex]);
        for (var i = lis.length - 1; i >= 0 ; i--) {
            if (g.options.items[i].closable) {
                g.doClose(i, $(lis[i]));
            }
            else if (!isActived) {
                isActived = (i == g.activedIndex);
            }
        }
        lis = $("." + g.liCss, g.tab.header.ul);
        if (!isActived && lis.length > 0) {
            g.activedId = null;
            g.activedIndex = null;
            g.active(0);
        } else {
            g.activedIndex = lis.index(activedTab);
        }
    },
    doClose: function (index, li) {
        var g = this, items = g.options.items, id;
        //找到当前页签的id
        var cmpContent = $(g.tab.content.children()[index]);
        id = cmpContent.attr("id");

        //触发关闭前事件
        if (g.beforeClose) {
            var flag = g.fireEvent("beforeClose", index);
            if (flag == false)
                return;
        }
        g.totalWidth -= li.width();
        //删除对应html元素
        li.remove();
        cmpContent.remove();
        //删除options中item
        items.splice(index, 1);
        //删除组件items中item,组件管理器删除组件，删除所有子组件
        var cmp = EIAP.getCmp(id);
        if (cmp) {
            var cmpItems = g.items;
            for (var j in cmpItems) {
                if (cmpItems[j] == id) {
                    cmpItems.splice(j, 1);
                    break;
                }
            }
            EIAP.remove(id);
        }
        //关闭后事件
        if (g.afterClose) {
            g.fireEvent("afterClose", index);
        }
    },
    refresh: function (index) {
        var g = this;
        var cmpContent = $(g.tab.content.children()[index]);
        var item = g.options.items[index];
        if (item.iframe) {
            if (g.mask) {
                g.mask.show();
            } else {
                var mask = EIAP.LoadMask(g);
                mask.show();
                g.mask = mask;
            }
            var url = cmpContent.attr("src");
            cmpContent.attr("src", url);
        }
        //        else {
        //            var divId = item.id || item.renderTo;
        //            cmpContent.after("<div id='" + divId + "'></div>");
        //            EIAP.remove(divId);
        //            g.preHandleItems(item);
        //            item.renderTo = divId;
        //            var fn = eval("EIAP." + item.xtype);
        //            fn.call(fn, item);
        //        }
    },
    preHandleItems: function (item) {
        var g = this;
        delete item.renderTo;
        if (item.xtype == "GridPanel") {
            EIAP.apply(item, {
                exportXls: false,
                showSearch: false,
                showRefresh: false
            });
        }
        if (item.items) {
            item.items.forEach(function (childItem) {
                g.preHandleItems(childItem);
            });
        }
    }
});﻿EIAP.FloatPanel = function (otps) {
    return new EIAP.FloatingPanel(otps);
};
EIAP.FloatingPanel = function (otps) {
    EIAP.apply(this, otps);
    this.initWin();
};
EIAP.FloatingPanel.prototype = {
    initWin: function () {
        this.win = EIAP.Window({
            title: this.title || "&#160;",
            left: 0,
            top: 0,
            shadow: true,
            resizable: false,
            showClose: this.showClose || false,
            showMax: false,
            showToggle: false,
            draggable: false,
            autoHeight: false,
            modal: this.modal || false,
            closeAction: this.closeAction || "hide",
            iconCls: this.iconCls || "",
            buttonAlign: "center",
            width: this.width || this.width,
            height: this.height || this.height,
            items: this.items || []
        });
        if (!this.title) {
            this.win.dom.header.height(7);
        }
        this.show();
    },
    width: 360,
    height: 200,
    isVisible: function () {
        return this.win && this.win.dom.is(":visible");
    },
    hide: function () {
        var g = this, win = g.win;
        if (win.dom.shadow) win.dom.shadow.hide();
        g.modal && win.unmask(g.win);
        win.dom.animate({ left: win.hideLeft, top: win.hideTop, opacity: 'hide' }, function () {
            if (g.closeAction == "close") {
                win.close();
            }
        });
    },
    show: function () {
        var win = this.win;
        win.left = this.left || 0.5 * ($(window).width() - win.dom.width());
        win.top = win.hideTop = -500;
        win.showTop = this.top || 1;
        win.showLeft = win.hideLeft = win.left;
        win.dom.css({
            "left": win.left,
            "top": win.top,
            "visibility": 'visible'
        });
        this.modal && win.mask(this.win);
        win.dom.show();
        win.dom.animate({ left: win.showLeft, top: win.showTop }, function () {
            win.shadow && win.dom.shadow && win.dom.shadow.updateShadow(win.dom);
        });
        win.setFront(win);

    }
};﻿EIAP.Layout = function () {
    return new EIAP.layout.Layout(arguments[0]);
};
EIAP.layout.Layout = EIAP.extend(EIAP.UIComponent, {
    topHeight: 60,
    bottomHeight: 60,
    leftWidth: 200,
    centerWidth: 300,
    rightWidth: 170,
    forceToFit: true,
    inWindow: false, // 是否以窗口的高度为准 height设置为百分比时可用
    heightDiff: 0, // 高度补差
    height: '100%', // 高度
    onHeightChanged: null,
    isLeftCollapse: false, // 初始化时 左边是否隐藏
    isRightCollapse: false, // 初始化时 右边是否隐藏
    allowLeftCollapse: true, // 是否允许 左边可以隐藏
    allowRightCollapse: true, // 是否允许 右边可以隐藏
    allowLeftResize: false, // 是否允许 左边可以调整大小
    allowRightResize: false, // 是否允许 右边可以调整大小
    allowTopResize: false, // 是否允许 头部可以调整大小
    allowBottomResize: false, // 是否允许 底部可以调整大小
    space: 3, // 间隔
    onEndResize: null, // 调整大小结束事件
    minLeftWidth: 80, // 调整左侧宽度时的最小允许宽度
    minRightWidth: 80,
    // 调整右侧宽度时的最小允许宽度
    initComponent: function () {
        EIAP.layout.Layout.superclass.initComponent.call(this);
    },
    __getType: function () {
        return 'Layout';
    },
    __idPrev: function () {
        return 'Layout';
    },
    _extMethods: function () {
        return EIAP.layout.Layout;
    },
    _render: function () {
        var g = this;
        g.layout = $(this.element);
        g.layout.addClass("ux-layout");
        g.width = g.layout.width();
        // top
        if ($("> div[region=top]", g.layout).length > 0) {
            g.top = $("> div[region=top]", g.layout)
					.wrap('<div class="ux-layout-top" style="top:0px;"></div>')
					.parent();
            g.top.content = $("> div[region=top]", g.top);
            if (!g.top.content.hasClass("ux-layout-content")) {
                g.top.content.addClass("ux-layout-content");
            }
            g.topHeight = g.topHeight;
            if (g.topHeight) {
                g.top.height(g.topHeight);
            }
            // set title
            var toptitle = g.top.content.attr("title");
            if (toptitle) {
                g.top.header = $('<div class="ux-layout-header"><div class="ux-layout-header-toggle"></div><div class="ux-layout-icon"></div><div class="ux-layout-header-inner"></div></div>');
                g.top.prepend(g.top.header);
                $(".ux-layout-header-inner", g.top.header).html(toptitle);
                g.top.content.attr("title", "");
                var tpicon = g.top.content.attr("iconCls");
                if (tpicon) {
                    $(".ux-layout-icon", g.top.header).addClass(tpicon).show();
                }
            }
        }
        // bottom
        if ($("> div[region=bottom]", g.layout).length > 0) {
            g.bottom = $("> div[region=bottom]", g.layout)
					.wrap('<div class="ux-layout-bottom"></div>').parent();
            g.bottom.content = $("> div[region=bottom]", g.bottom);
            if (!g.bottom.content.hasClass("ux-layout-content")) {
                g.bottom.content.addClass("ux-layout-content");
            }
            g.bottomHeight = g.bottomHeight;
            if (g.bottomHeight) {
                g.bottom.height(g.bottomHeight);
            }
            // set title
            var bottomtitle = g.bottom.content.attr("title");
            if (bottomtitle) {
                g.bottom.header = $('<div class="ux-layout-header"><div class="ux-layout-header-toggle"></div><div class="ux-layout-icon"></div><div class="ux-layout-header-inner"></div></div>');
                g.bottom.prepend(g.bottom.header);
                $(".ux-layout-header-inner", g.bottom.header).html(bottomtitle);
                g.bottom.content.attr("title", "");
                var bticon = g.bottom.content.attr("iconCls");
                if (bticon) {
                    $(".ux-layout-icon", g.bottom.header).addClass(bticon)
							.show();
                }
            }
        }
        // left
        if ($("> div[region=left]", g.layout).length > 0) {
            g.left = $("> div[region=left]", g.layout)
					.wrap('<div class="ux-layout-left" style="left:0px;"></div>')
					.parent();
            g.left.header = $('<div class="ux-layout-header"><div class="ux-layout-header-toggle"></div><div class="ux-layout-icon"></div><div class="ux-layout-header-inner"></div></div>');
            g.left.prepend(g.left.header);
            g.left.header.toggle = $(".ux-layout-header-toggle", g.left.header);
            g.left.content = $("> div[region=left]", g.left);
            if (!g.left.content.hasClass("ux-layout-content")) {
                g.left.content.addClass("ux-layout-content");
            }
            if (!g.allowLeftCollapse) {
                $(".ux-layout-header-toggle", g.left.header).remove();
            }
            // set title
            var lefttitle = g.left.content.attr("title");
            if (lefttitle) {
                g.left.content.attr("title", "");
                $(".ux-layout-header-inner", g.left.header).html(lefttitle);
                var lefticon = g.left.content.attr("iconCls");
                if (lefticon) {
                    $(".ux-layout-icon", g.left.header).addClass(lefticon)
							.show();
                }
            }
            // set width
            g.leftWidth = g.leftWidth;
            if (g.leftWidth) {
                g.left.width(g.leftWidth);
            }
            if (g.leftTbar && EIAP.toolbar.ToolBar) {
                g.left.tbar = $("<div></div>").attr("id", "tbar-layout-left-" + g.id);
                g.left.tbar.addClass("ux-toolbar-tbar");
                g.left.content.prepend(g.left.tbar);
                EIAP.ToolBar({
                    renderTo: "tbar-layout-left-" + g.id,
                    items: g.leftTbar
                });
            }
        }
        // center
        if ($("> div[region=center]", g.layout).length > 0) {
            g.center = $("> div[region=center]", g.layout).wrap('<div class="ux-layout-center" ></div>').parent();
            g.center.content = $("> div[region=center]", g.center);
            g.center.content.addClass("ux-layout-content");
            // set title
            var centertitle = g.center.content.attr("title");
            if (centertitle) {
                g.center.content.attr("title", "");
                g.center.header = $('<div class="ux-layout-header"><div class="ux-layout-icon"></div><div class="ux-layout-header-inner"></div></div>');
                g.center.prepend(g.center.header);
                $(".ux-layout-header-inner", g.center.header).html(centertitle);
                var cicon = g.center.content.attr("iconCls");
                if (cicon) {
                    $(".ux-layout-icon", g.center.header).addClass(cicon)
							.show();
                }
            }
            // set width
            g.centerWidth = g.centerWidth;
            if (g.centerWidth) {
                g.center.width(g.centerWidth);
            }
        }
        // right
        if ($("> div[region=right]", g.layout).length > 0) {
            g.right = $("> div[region=right]", g.layout).wrap('<div class="ux-layout-right"></div>').parent();
            g.right.header = $('<div class="ux-layout-header"><div class="ux-layout-header-toggle"></div><div class="ux-layout-icon"></div><div class="ux-layout-header-inner"></div></div>');
            g.right.prepend(g.right.header);
            g.right.header.toggle = $(".ux-layout-header-toggle", g.right.header);
            if (!g.allowRightCollapse) {
                $(".ux-layout-header-toggle", g.right.header).remove();
            }
            g.right.content = $("> div[region=right]", g.right);
            if (!g.right.content.hasClass("ux-layout-content")) {
                g.right.content.addClass("ux-layout-content");
            }
            // set title
            var righttitle = g.right.content.attr("title");
            if (righttitle) {
                g.right.content.attr("title", "");
                $(".ux-layout-header-inner", g.right.header).html(righttitle);
                var ricon = g.right.content.attr("iconCls");
                if (ricon) {
                    $(".ux-layout-icon", g.right.header).addClass(ricon).show();
                }
            }
            // set width
            g.rightWidth = g.rightWidth;
            if (g.rightWidth) {
                g.right.width(g.rightWidth);
            }
        }
        var layoutparent = g._getLayoutPrent();
        if (g.inWindow || layoutparent[0].tagName.toLowerCase() == "body") {
            layoutparent.addClass("ux-layout-bg");
        } else {
            g.layout.addClass("ux-layout-bg").removeClass("ux-layout-content");
        }
        // lock
        g.layout.lock = $("<div class='ux-layout-lock'></div>");
        g.layout.append(g.layout.lock);
        // DropHandle
        g._addDropHandle();
        // Collapse
        g.isLeftCollapse = g.isLeftCollapse;
        g.isRightCollapse = g.isRightCollapse;
        g.leftCollapse = $('<div class="ux-layout-collapse-left" style="display: none; "><div class="ux-layout-collapse-left-toggle"></div></div>');
        g.rightCollapse = $('<div class="ux-layout-collapse-right" style="display: none; "><div class="ux-layout-collapse-right-toggle"></div></div>');
        g.layout.append(g.leftCollapse).append(g.rightCollapse);
        g.leftCollapse.toggle = $("> .ux-layout-collapse-left-toggle", g.leftCollapse);
        g.rightCollapse.toggle = $("> .ux-layout-collapse-right-toggle", g.rightCollapse);
        g._setCollapse();
        // init
        g._bulid();
        g.set(g);
        g.onResize();
    },
    setLeftCollapse: function (isCollapse) {
        var g = this;
        if (g.left) {
            g.isLeftCollapse = isCollapse;
            if (g.isLeftCollapse) {
                g.leftCollapse.show();
                g.leftDropHandle && g.leftDropHandle.hide();
                g.left.hide();
            } else {
                g.leftCollapse.hide();
                g.leftDropHandle && g.leftDropHandle.show();
                g.left.show();
            }
            EIAP.resizeAll(g);
        }
    },
    setRightCollapse: function (isCollapse) {
        var g = this;
        if (g.right) {
            g.isRightCollapse = isCollapse;
            g.onResize();
            if (g.isRightCollapse) {
                g.rightCollapse.show();
                g.rightDropHandle && g.rightDropHandle.hide();
                g.right.hide();
            } else {
                g.rightCollapse.hide();
                g.rightDropHandle && g.rightDropHandle.show();
                g.right.show();
            }
            EIAP.resizeAll(g);
        }
    },
    _bulid: function () {
        var g = this;
        $(".ux-layout-header-toggle", g.layout).hover(function () { $(this).addClass("ux-layout-header-toggle-over"); }, function () { $(this).removeClass("ux-layout-header-toggle-over"); });
        $(".ux-layout-header-toggle", g.left).click(function () {
            g.setLeftCollapse(true);
        });
        $(".ux-layout-header-toggle", g.right).click(function () {
            g.setRightCollapse(true);
        });
        // set top
        g.middleTop = 0;
        if (g.top) {
            g.middleTop += g.top.height();
            g.middleTop += parseInt(g.top.css('borderTopWidth')) || 0;
            g.middleTop += parseInt(g.top.css('borderBottomWidth')) || 0;
            g.middleTop += g.space;
        }
        if (g.left) {
            g.left.css({
                top: g.middleTop
            });
            g.leftCollapse.css({
                top: g.middleTop
            });
        }
        if (g.center)
            g.center.css({
                top: g.middleTop
            });
        if (g.right) {
            g.right.css({
                top: g.middleTop
            });
            g.rightCollapse.css({
                top: g.middleTop
            });
        }
        // set left
        if (g.left)
            g.left.css({
                left: 0
            });
        g.onResize();
    },
    _setCollapse: function () {
        var g = this;
        g.leftCollapse.hover(function () {
            $(this).addClass("ux-layout-collapse-left-over");
        }, function () {
            $(this).removeClass("ux-layout-collapse-left-over");
        });
        g.leftCollapse.toggle.hover(function () {
            $(this).addClass("ux-layout-collapse-left-toggle-over");
        }, function () {
            $(this).removeClass("ux-layout-collapse-left-toggle-over");
        });
        g.rightCollapse.hover(function () {
            $(this).addClass("ux-layout-collapse-right-over");
        }, function () {
            $(this).removeClass("ux-layout-collapse-right-over");
        });
        g.rightCollapse.toggle.hover(function () {
            $(this).addClass("ux-layout-collapse-right-toggle-over");
        }, function () {
            $(this).removeClass("ux-layout-collapse-right-toggle-over");
        });
        g.leftCollapse.toggle.click(function () {
            g.setLeftCollapse(false);
        });
        g.rightCollapse.toggle.click(function () {
            g.setRightCollapse(false);
        });
        if (g.left && g.isLeftCollapse) {
            g.leftCollapse.show();
            g.leftDropHandle && g.leftDropHandle.hide();
            g.left.hide();
        }
        if (g.right && g.isRightCollapse) {
            g.rightCollapse.show();
            g.rightDropHandle && g.rightDropHandle.hide();
            g.right.hide();
        }
    },
    _addDropHandle: function () {
        var g = this;
        if (g.left && g.allowLeftResize) {
            g.leftDropHandle = $("<div class='ux-layout-drophandle-left'></div>");
            g.layout.append(g.leftDropHandle);
            g.leftDropHandle && g.leftDropHandle.show();
            g.leftDropHandle.mousedown(function (e) {
                g._start('leftresize', e);
            });
        }
        if (g.right && g.allowRightResize) {
            g.rightDropHandle = $("<div class='ux-layout-drophandle-right'></div>");
            g.layout.append(g.rightDropHandle);
            g.rightDropHandle && g.rightDropHandle.show();
            g.rightDropHandle.mousedown(function (e) {
                g._start('rightresize', e);
            });
        }
        if (g.top && g.allowTopResize) {
            g.topDropHandle = $("<div class='ux-layout-drophandle-top'></div>");
            g.layout.append(g.topDropHandle);
            g.topDropHandle.show();
            g.topDropHandle.mousedown(function (e) {
                g._start('topresize', e);
            });
        }
        if (g.bottom && g.allowBottomResize) {
            g.bottomDropHandle = $("<div class='ux-layout-drophandle-bottom'></div>");
            g.layout.append(g.bottomDropHandle);
            g.bottomDropHandle.show();
            g.bottomDropHandle.mousedown(function (e) {
                g._start('bottomresize', e);
            });
        }
        g.draggingxline = $("<div class='ux-layout-dragging-xline'></div>");
        g.draggingyline = $("<div class='ux-layout-dragging-yline'></div>");
        g.layout.append(g.draggingxline).append(g.draggingyline);
    },
    _setDropHandlePosition: function () {
        var g = this;
        if (g.leftDropHandle) {
            g.leftDropHandle.css({
                left: g.left.width() + parseInt(g.left.css('left')),
                height: g.middleHeight,
                top: g.middleTop
            });
        }
        if (g.rightDropHandle) {
            g.rightDropHandle.css({
                left: parseInt(g.right.css('left')) - g.space,
                height: g.middleHeight,
                top: g.middleTop
            });
        }
        if (g.topDropHandle) {
            g.topDropHandle.css({
                top: g.top.height() + parseInt(g.top.css('top')),
                width: g.top.width()
            });
        }
        if (g.bottomDropHandle) {
            g.bottomDropHandle.css({
                top: parseInt(g.bottom.css('top')) - g.space,
                width: g.bottom.width()
            });
        }
    },
    _getLayoutPrent: function () {
        return this.layout.parent();
    },

    onResize: function () {
        var g = this;
        var oldheight = g.layout.height();
        // set layout height
        var h = 0, parentHeight = null;
        if (typeof (g.height) == "string" && g.height.indexOf('%') > 0) {
            var layoutparent = g._getLayoutPrent();
            if (g.inWindow || layoutparent[0].tagName.toLowerCase() == "body") {
                parentHeight = $(window).height();
                parentHeight -= parseInt($('body').css('paddingTop'));
                parentHeight -= parseInt($('body').css('paddingBottom'));
                g.layout.css({ "margin": g.space });
                parentHeight -= parseInt(g.layout.css('marginBottom'));
                $('body').css({ "overflow": "hidden" });
                var w = $(window).width();
                w -= parseInt(g.layout.css('marginLeft'));
                w -= parseInt(g.layout.css('marginRight'));
                g.layout.width(w);

            } else {
                parentHeight = layoutparent.height();
                if (g.top)
                    g.top.css({
                        "border-left-style": "none",
                        "border-top-style": "none",
                        "border-right-style": "none"
                    });
                if (g.left)
                    g.left.css({
                        "border-left-style": "none"
                    });
                if (g.right)
                    g.right.css({
                        "border-right-style": "none"
                    });
                if (g.bottom)
                    g.bottom.css({
                        "border-left-style": "none",
                        "border-bottom-style": "none",
                        "border-right-style": "none"
                    });
            }
            h = parentHeight * parseFloat(g.height) * 0.01;
            if (g.inWindow || layoutparent[0].tagName.toLowerCase() == "body") {
                h -= (g.layout.offset().top);
            }
        } else {
            h = parseInt(g.height);
        }
        h += g.heightDiff;
        g.layout.height(h);
        g.layoutHeight = g.layout.height();
        g.middleWidth = g.layout.width();
        g.middleHeight = g.layout.height();
        if (g.top) {
            g.middleHeight -= g.top.height();
            g.middleHeight -= parseInt(g.top.css('borderTopWidth')) || 0;
            g.middleHeight -= parseInt(g.top.css('borderBottomWidth')) || 0;
            g.middleHeight -= g.space;
            g.top.width(g.middleWidth - parseInt(g.layout.css("marginRight")) || 0);
        }
        if (g.bottom) {
            g.middleHeight -= g.bottom.height();
            g.middleHeight -= parseInt(g.bottom.css('borderTopWidth')) || 0;
            g.middleHeight -= parseInt(g.bottom.css('borderBottomWidth')) || 0;
            g.middleHeight -= g.space;
            g.bottom.width(g.middleWidth - parseInt(g.layout.css("marginRight")) || 0);
        }
        // specific
        g.middleHeight -= 2;
        if (g.hasBind('heightChanged') && g.layoutHeight != oldheight) {
            g.trigger('heightChanged', [{
                layoutHeight: g.layoutHeight,
                diff: g.layoutHeight - oldheight,
                middleHeight: g.middleHeight
            }]);
        }

        if (g.center) {
            g.centerWidth = g.middleWidth;
            if (g.left) {
                if (g.isLeftCollapse) {
                    g.centerWidth -= g.leftCollapse.outerWidth();
                    g.centerWidth -= parseInt(g.leftCollapse.css('left')) || 0;
                    g.centerWidth -= g.space;
                } else {
                    g.centerWidth -= g.left.outerWidth();
                    g.centerWidth -= parseInt(g.left.css('left')) || 0;
                    g.centerWidth -= g.space;
                }
                g.centerWidth -= parseInt(g.layout.css("marginRight")) || 0;
            }
            if (g.right) {
                if (g.isRightCollapse) {
                    g.centerWidth -= g.rightCollapse.outerWidth();
                    g.rightCollapse.css({ left: parseInt(g.right.css('left')) || 0 });
                    g.centerWidth -= g.space;
                } else {
                    g.centerWidth -= g.right.outerWidth();
                    g.centerWidth -= g.space;
                }
            }
            g.centerLeft = 0;
            if (g.left) {
                if (g.isLeftCollapse) {
                    g.centerLeft += g.leftCollapse.outerWidth();
                    g.centerLeft += parseInt(g.leftCollapse.css('left'));
                    g.centerLeft += g.space;
                } else {
                    g.centerLeft += g.left.outerWidth();
                    g.centerLeft += g.space;
                }
            }
            g.center.css({
                left: g.centerLeft
            });
            g.center.width(g.centerWidth);
            g.center.height(g.middleHeight);
            var contentHeight = g.middleHeight;
            if (g.center.header)
                contentHeight -= g.center.header.height();
            g.center.content.height(contentHeight);
        }
        if (g.left) {
            g.leftCollapse.height(g.middleHeight);
            g.left.height(g.middleHeight);
        }
        if (g.right) {
            g.rightCollapse.height(g.middleHeight);
            g.right.height(g.middleHeight);
            // set left
            g.rightLeft = 0;
            if (g.left) {
                if (g.isLeftCollapse) {
                    g.rightLeft += g.leftCollapse.width();
                    g.rightLeft += parseInt(g.leftCollapse
							.css('borderLeftWidth'));
                    g.rightLeft += parseInt(g.leftCollapse
							.css('borderRightWidth'));
                    g.rightLeft += g.space;
                } else {
                    g.rightLeft += g.left.width();
                    g.rightLeft += parseInt(g.left.css('borderLeftWidth'));
                    g.rightLeft += parseInt(g.left.css('borderRightWidth'));
                    g.rightLeft += parseInt(g.left.css('left'));
                    g.rightLeft += g.space;
                }
            }
            if (g.center) {
                g.rightLeft += g.center.width();
                g.rightLeft += parseInt(g.center.css('borderLeftWidth'));
                g.rightLeft += parseInt(g.center.css('borderRightWidth'));
                g.rightLeft += g.space;
            }
            g.right.css({
                left: g.rightLeft
            });
        }
        if (g.bottom) {
            g.bottomTop = g.layoutHeight - g.bottom.height();
            if (g.inWindow
					|| g._getLayoutPrent()[0].tagName.toLowerCase() == "body") {
                g.bottomTop -= 2;
            }
            g.bottom.css({
                top: g.bottomTop
            });
        }
        g._setDropHandlePosition();

    },
    _start: function (dragtype, e) {
        var g = this;
        g.dragtype = dragtype;
        if (dragtype == 'leftresize' || dragtype == 'rightresize') {
            g.xresize = {
                startX: e.pageX
            };
            g.draggingyline.css({
                left: e.pageX - g.layout.offset().left,
                height: g.middleHeight,
                top: g.middleTop
            }).show();
            $('body').css('cursor', 'col-resize');
        } else if (dragtype == 'topresize' || dragtype == 'bottomresize') {
            g.yresize = {
                startY: e.pageY
            };
            g.draggingxline.css({
                top: e.pageY - g.layout.offset().top,
                width: g.layout.width()
            }).show();
            $('body').css('cursor', 'row-resize');
        } else {
            return;
        }

        g.layout.lock.width(g.layout.width());
        g.layout.lock.height(g.layout.height());
        g.layout.lock.show();
        if ($.browser.msie || $.browser.safari)
            $('body').bind('selectstart', function () {
                return false;
            }); // 不能选择

        $(document).bind('mouseup', function () {
            g._stop.apply(g, arguments);
        });
        $(document).bind('mousemove', function () {
            g._drag.apply(g, arguments);
        });
    },
    _drag: function (e) {
        var g = this;
        if (g.xresize) {
            g.xresize.diff = e.pageX - g.xresize.startX;
            g.draggingyline.css({
                left: e.pageX - g.layout.offset().left
            });
            $('body').css('cursor', 'col-resize');
        } else if (g.yresize) {
            g.yresize.diff = e.pageY - g.yresize.startY;
            g.draggingxline.css({
                top: e.pageY - g.layout.offset().top
            });
            $('body').css('cursor', 'row-resize');
        }
    },
    _stop: function (e) {
        var g = this;
        var diff;
        if (g.xresize && g.xresize.diff != undefined) {
            diff = g.xresize.diff;
            if (g.dragtype == 'leftresize') {
                if (g.minLeftWidth) {
                    if (g.leftWidth + g.xresize.diff < g.minLeftWidth)
                        return;
                }
                g.leftWidth += g.xresize.diff;
                g.left.width(g.leftWidth);
                if (g.center)
                    g.center.width(g.center.width() - g.xresize.diff).css({
                        left: parseInt(g.center.css('left'))
										+ g.xresize.diff
                    });
                else if (g.right)
                    g.right.width(g.left.width() - g.xresize.diff).css({
                        left: parseInt(g.right.css('left'))
										+ g.xresize.diff
                    });
            } else if (g.dragtype == 'rightresize') {
                if (g.minRightWidth) {
                    if (g.rightWidth - g.xresize.diff < g.minRightWidth)
                        return;
                }
                g.rightWidth -= g.xresize.diff;
                g.right.width(g.rightWidth).css({
                    left: parseInt(g.right.css('left'))
									+ g.xresize.diff
                });
                if (g.center)
                    g.center.width(g.center.width() + g.xresize.diff);
                else if (g.left)
                    g.left.width(g.left.width() + g.xresize.diff);
            }
        } else if (g.yresize && g.yresize.diff != undefined) {
            diff = g.yresize.diff;
            if (g.dragtype == 'topresize') {
                g.top.height(g.top.height() + g.yresize.diff);
                g.middleTop += g.yresize.diff;
                g.middleHeight -= g.yresize.diff;
                if (g.left) {
                    g.left.css({
                        top: g.middleTop
                    }).height(g.middleHeight);
                    g.leftCollapse.css({
                        top: g.middleTop
                    }).height(g.middleHeight);
                }
                if (g.center)
                    g.center.css({
                        top: g.middleTop
                    }).height(g.middleHeight);
                if (g.right) {
                    g.right.css({
                        top: g.middleTop
                    }).height(g.middleHeight);
                    g.rightCollapse.css({
                        top: g.middleTop
                    }).height(g.middleHeight);
                }
            } else if (g.dragtype == 'bottomresize') {
                g.bottom.height(g.bottom.height() - g.yresize.diff);
                g.middleHeight += g.yresize.diff;
                g.bottomTop += g.yresize.diff;
                g.bottom.css({
                    top: g.bottomTop
                });
                if (g.left) {
                    g.left.height(g.middleHeight);
                    g.leftCollapse.height(g.middleHeight);
                }
                if (g.center)
                    g.center.height(g.middleHeight);
                if (g.right) {
                    g.right.height(g.middleHeight);
                    g.rightCollapse.height(g.middleHeight);
                }
            }
        }
        g.trigger('endResize', [{
            direction: g.dragtype
							? g.dragtype.replace(/resize/, '')
							: '',
            diff: diff
        }, e]);
        g._setDropHandlePosition();
        g.draggingxline.hide();
        g.draggingyline.hide();
        g.xresize = g.yresize = g.dragtype = false;
        g.layout.lock.hide();
        if ($.browser.msie || $.browser.safari)
            $('body').unbind('selectstart');
        $(document).unbind('mousemove', g._drag);
        $(document).unbind('mouseup', g._stop);
        $('body').css('cursor', '');
        EIAP.resizeAll();
    }
});
﻿EIAP.BorderLayout = function () {
    return new EIAP.layout.BorderLayout(arguments[0], arguments[1]);
};

EIAP.layout.BorderLayout = function () {
    this.scope = arguments[0];
    var type = arguments[1];
    if (type == "layout") {
        this.layout();
    } else if (type == "resize") {
        this.resize();
    }
};

EIAP.apply(EIAP.layout.BorderLayout.prototype, {
    toolBoxCss: "ux-layout-borderbox",
    upCss: "ux-layout-border-up",
    downCss: "ux-layout-border-down",
    leftCss: "ux-layout-border-left",
    rightCss: "ux-layout-border-right",
    collapsedCss: "ux-layout-collapsed",

    layout: function () {
        var items = this.scope.options.items, g = this, scope = this.scope;
        var east, south, west, north, center;
        var dom = this.scope.getDom();
        var parentWidth = dom.width();
        var parentHeight = dom.height();
        var centerWidth = parentWidth;
        var centerHeight = parentHeight;
        for (var i = 0; i < items.length; i++) {
            var item = items[i];
            item.collapsedCss = g.collapsedCss;
            EIAP.applyIf(item, { border: true, xtype: "Panel" });
            if (item.region == "east") {
                item.toggleCss = g.rightCss;
                item.collapse = null;
                item.expand = null;
                if (!item.width) {
                    item.width = "20%";
                    item.defaultWidth = "20%";
                }
                east = item;
                if (typeof east.width == "string" && east.width.indexOf("%") > -1) {
                    width = parseFloat(east.width) / 100;
                    east.width = parseInt(parentWidth * width);
                }
                centerWidth -= (east.width + this.scope.space);
            }
            else if (item.region == "west") {
                item.toggleCss = g.leftCss;
                item.collapse = null;
                item.expand = null;
                if (!item.width) {
                    item.width = "20%";
                    item.defaultWidth = "20%";
                }
                west = item;
                if (typeof west.width == "string" && west.width.indexOf("%") > -1) {
                    width = parseFloat(west.width) / 100;
                    west.width = parseInt(parentWidth * width);
                }
                centerWidth -= (west.width + this.scope.space);
            }
            else if (item.region == "south") {
                item.toggleCss = g.downCss;
                item.collapse = function () { g.collapseSouth(); };
                item.expand = function () { g.expandSouth(); };
                if (!item.height) {
                    item.height = "15%";
                    item.defaultHeight = "15%";
                }
                south = item;
                if (typeof south.height == "string" && south.height.indexOf("%") > -1) {
                    height = parseFloat(south.height) / 100;
                    south.height = parseInt(parentHeight * height);
                    south.defaultHeight = "15%";
                }
                centerHeight -= (south.height + this.scope.space);
            }
            else if (item.region == "north") {
                item.toggleCss = g.upCss;
                item.collapse = function () { g.collapseNorth(); };
                item.expand = function () { g.expandNorth(); };
                if (!item.height) {
                    item.height = "15%";
                    item.defaultHeight = "15%";
                }
                north = item;
                if (typeof north.height == "string" && north.height.indexOf("%") > -1) {
                    height = parseFloat(north.height) / 100;
                    north.height = parseInt(parentHeight * height);
                }
                centerHeight -= (north.height + this.scope.space);
            }
            else if (item.region == "center") {
                center = item;
            }
        }

        if (!center) {
            throw new Error(EIAP.error.noCenter);
        } else {
            center.width = centerWidth;
            center.height = centerHeight;
            var parentPos = dom.offset();
            var height, width, panel, top, left = parentPos.left;
            var div, id, xtype, cmp;
            if (north) {
                xtype = north.xtype ? north.xtype : scope.defaultType;
                EIAP.applyIf(north, this.defaultStyle);
                id = north.id || EIAP.getId(xtype);
                div = $("<div id='" + id + "'></div>");
                dom.append(div);
                div.css({
                    "position": "absolute"
                });
                north.renderTo = id;
                cmp = eval("EIAP." + xtype);
                if (!cmp) {
                    throw new Error(String.format(EIAP.error.noCmp, xtype));
                }
                panel = cmp.call(cmp, north);
                scope.items.push(panel.id);
                this.scope.north = panel.id;
                top = panel.height + panel.dom.offset().top + panel.space;
            }
            if (west) {
                west.height = center.height;
                xtype = west.xtype ? west.xtype : scope.defaultType;
                EIAP.applyIf(west, this.defaultStyle);
                cmp = eval("EIAP." + xtype);
                if (!cmp) {
                    throw new Error(String.format(EIAP.error.noCmp, xtype));
                }
                id = west.id || EIAP.getId(xtype);
                div = $("<div id='" + id + "'></div>");
                dom.append(div);
                div.css({
                    "position": "absolute"
                });
                if (north)
                    div.offset({ top: top });
                west.renderTo = id;
                panel = cmp.call(cmp, west);
                scope.items.push(panel.id);
                this.scope.west = panel.id;
                if (west.collapsible) {
                    panel.dom.header.toolbox.bind("click", function () { g.collapseWest(); });
                }
                left = panel.width + panel.dom.offset().left + panel.space;
            }
            if (center) {
                xtype = center.xtype ? center.xtype : scope.defaultType;
                EIAP.applyIf(center, this.defaultStyle);
                cmp = eval("EIAP." + xtype);
                if (!cmp) {
                    throw new Error(String.format(EIAP.error.noCmp, xtype));
                }
                id = center.id || EIAP.getId(xtype);
                div = $("<div id='" + id + "'></div>");
                dom.append(div);
                div.css({
                    "position": "absolute"
                });
                if (north)
                    div.offset({ top: top });
                if (west)
                    div.offset({ left: left });
                center.renderTo = id;
                panel = cmp.call(cmp, center);
                scope.items.push(panel.id);
                this.scope.center = panel.id;
                left += panel.width + panel.space;
            }
            if (east) {
                east.height = center.height;
                xtype = east.xtype ? east.xtype : scope.defaultType;
                EIAP.applyIf(east, this.defaultStyle);
                cmp = eval("EIAP." + xtype);
                if (!cmp) {
                    throw new Error(String.format(EIAP.error.noCmp, xtype));
                }
                id = east.id || EIAP.getId(xtype);
                div = $("<div id='" + id + "'></div>");
                dom.append(div);
                div.css({
                    "position": "absolute"
                });
                if (north)
                    div.offset({ top: top });
                east.renderTo = id;
                panel = cmp.call(cmp, east);
                div.offset({ left: (!west) ? (left + EIAP.getCmp(this.scope.center).dom.offset().left) : left });
                scope.items.push(panel.id);
                this.scope.east = panel.id;
                if (east.collapsible) {
                    panel.dom.header.toolbox.bind("click", function () { g.collapseEast(); });
                }
            }
            top = EIAP.getCmp(this.scope.center).dom.offset().top + EIAP.getCmp(this.scope.center).height + panel.space;
            if (south) {
                south.height = south.height;
                xtype = south.xtype ? south.xtype : scope.defaultType;
                EIAP.applyIf(south, this.defaultStyle);
                cmp = eval("EIAP." + xtype);
                if (!cmp) {
                    throw new Error(String.format(EIAP.error.noCmp, xtype));
                }
                id = south.id || EIAP.getId(xtype);
                div = $("<div id='" + id + "'></div>");
                dom.append(div);
                div.css({
                    "position": "absolute"
                });
                south.renderTo = id;
                panel = cmp.call(cmp, south);
                div.offset({ top: top });
                scope.items.push(panel.id);
                this.scope.south = panel.id;
            }
        }
    },
    collapseNorth: function () {
        var scope = this.scope, north = EIAP.getCmp(scope.north), east = EIAP.getCmp(scope.east), west = EIAP.getCmp(scope.west), center = EIAP.getCmp(scope.center);
        var top = north.dom.content.bwrap.offset().top + north.space + (parseFloat(north.dom.css("borderBottomWidth")) || 0);
        var height = center.dom.outerHeight() + north.dom.content.bwrap.outerHeight();
        north.dom.header.toolbox.removeClass(this.upCss).addClass(this.downCss);
        north.dom.content.bwrap.hide();
        north.collapsed = true;
        center.setHeight(height);
        center.dom.offset({ top: top });
        if (west) {
            west.setHeight(height);
            if (west.collapsed) {
                west.collDiv.height(height - 2 * (parseFloat(west.collDiv.css("borderBottomWidth")) || 0));
                west.collDiv.offset({ top: top });
                west.dom.show();
                west.dom.offset({ top: top });
                west.dom.hide();
            } else {
                west.dom.offset({ top: top });
            }
            EIAP.resize(west);
        }
        if (east) {
            east.setHeight(height);
            if (east.collapsed) {
                east.collDiv.height(height - 2 * (parseFloat(east.collDiv.css("borderBottomWidth")) || 0));
                east.collDiv.offset({ top: top });
                east.dom.show();
                east.dom.offset({ top: top });
                east.dom.hide();
            } else {
                east.dom.offset({ top: top });
            }
            EIAP.resize(east);
        }
        EIAP.resize(center);
    },
    expandNorth: function () {
        var scope = this.scope, north = EIAP.getCmp(scope.north), east = EIAP.getCmp(scope.east), west = EIAP.getCmp(scope.west), center = EIAP.getCmp(scope.center);
        north.dom.header.toolbox.addClass(this.upCss).removeClass(this.downCss);
        north.dom.content.bwrap.show();
        north.collapsed = false;
        var top = center.dom.offset().top + north.dom.content.bwrap.outerHeight();
        var height = center.dom.outerHeight() - north.dom.content.bwrap.outerHeight();
        center.setHeight(height);
        center.dom.offset({ top: top });
        if (west) {
            west.setHeight(height);
            if (west.collapsed) {
                west.collDiv.height(height - 2 * (parseFloat(west.collDiv.css("borderBottomWidth")) || 0));
                west.collDiv.offset({ top: top });
                west.dom.show();
                west.dom.offset({ top: top });
                west.dom.hide();
            } else {
                west.dom.offset({ top: top });
            }
            EIAP.resize(west);
        }
        if (east) {
            east.setHeight(height);
            if (east.collapsed) {
                east.collDiv.height(height - 2 * (parseFloat(east.collDiv.css("borderBottomWidth")) || 0));
                east.collDiv.offset({ top: top });
                east.dom.show();
                east.dom.offset({ top: top });
                east.dom.hide();
            } else {
                east.dom.offset({ top: top });
            }
            EIAP.resize(east);
        }
        EIAP.resize(center);
    },
    collapseWest: function () {
        var g = this, scope = this.scope, west = EIAP.getCmp(scope.west), div = west.collDiv, center = EIAP.getCmp(scope.center);
        if (!div) {
            div = $("<div></div>").addClass(g.collapsedCss);
            div.append($("<div></div>").addClass(g.toolBoxCss).addClass(g.rightCss).bind("click", function () {
                g.expandWest();
            }));
            west.dom.before(div);
            west.collDiv = div;
        } else {
            div.show();
        }
        var top = west.dom.offset().top;
        div.css({
            "position": "absolute",
            height: west.dom.height()
        });
        if (EIAP.getCmp(scope.north)) {
            div.offset({ top: top });
        }
        west.collapsed = true;
        var left = div.offset().left + div.outerWidth() + west.space;
        var width = center.dom.outerWidth() - div.outerWidth() + west.dom.outerWidth();
        west.dom.hide();
        center.setWidth(width);
        center.dom.offset({ left: left });
        EIAP.resize(center);
    },
    expandWest: function () {
        var scope = this.scope, west = EIAP.getCmp(scope.west), div = west.collDiv, center = EIAP.getCmp(scope.center);
        west.dom.show();
        var left = west.dom.offset().left + west.dom.outerWidth() + west.space;
        var width = center.dom.outerWidth() + div.outerWidth() - west.dom.outerWidth();
        div.hide();
        west.collapsed = false;
        center.setWidth(width);
        center.dom.offset({ left: left });
        EIAP.resize(center);
    },
    collapseEast: function () {
        var g = this, scope = this.scope, east = EIAP.getCmp(scope.east), div = east.collDiv, center = EIAP.getCmp(scope.center);
        if (!div) {
            div = $("<div></div>").addClass(g.collapsedCss);
            div.append($("<div></div>").addClass(g.toolBoxCss).addClass(g.leftCss).bind("click", function () {
                g.expandEast();
            }));
            east.dom.before(div);
            east.collDiv = div;
        } else {
            div.show();
        }
        var top = east.dom.offset().top;
        var left = east.dom.offset().left - div.outerWidth() + east.dom.outerWidth();
        div.css({
            "position": "absolute",
            height: east.dom.height()
        });
        if (EIAP.getCmp(scope.north)) {
            div.offset({ top: top });
        }
        div.offset({ left: left });
        east.collapsed = true;
        var width = center.dom.outerWidth() - div.outerWidth() + east.dom.outerWidth();
        east.dom.hide();
        center.setWidth(width);
        EIAP.resize(center);
    },
    expandEast: function () {
        var scope = this.scope, east = EIAP.getCmp(scope.east), div = east.collDiv, center = EIAP.getCmp(scope.center);
        east.dom.show();
        var width = center.dom.outerWidth() + div.outerWidth() - east.dom.outerWidth();
        div.hide();
        east.collapsed = false;
        center.setWidth(width);
        var left = center.dom.offset().left + width + east.space;
        east.dom.offset({ left: left });
        EIAP.resize(center);
    },
    collapseSouth: function () {
        var scope = this.scope, south = EIAP.getCmp(scope.south), east = EIAP.getCmp(scope.east), west = EIAP.getCmp(scope.west), center = EIAP.getCmp(scope.center);
        var height = center.dom.outerHeight() + south.dom.content.bwrap.outerHeight();
        var top = south.dom.offset().top + south.dom.content.bwrap.outerHeight();
        south.dom.header.show();
        south.dom.header.toolbox.removeClass(this.downCss).addClass(this.upCss);
        south.dom.content.bwrap.hide();
        south.collapsed = true;
        south.dom.offset({ top: top });
        if (west) {
            if (west.collapsed) {
                west.collDiv.height(height - 2 * (parseFloat(west.collDiv.css("borderBottomWidth")) || 0));
            }
            west.setHeight(height);
            EIAP.resize(west);
        }
        if (east) {
            if (east.collapsed) {
                east.collDiv.height(height - 2 * (parseFloat(east.collDiv.css("borderBottomWidth")) || 0));
            }
            east.setHeight(height);
            EIAP.resize(east);
        }
        center.setHeight(height);
        EIAP.resize(center);
    },

    expandSouth: function () {
        var scope = this.scope, south = EIAP.getCmp(scope.south), east = EIAP.getCmp(scope.east), west = EIAP.getCmp(scope.west), center = EIAP.getCmp(scope.center);
        south.dom.content.bwrap.show();
        south.dom.header.toolbox.removeClass(this.upCss).addClass(this.downCss);
        var height = center.dom.outerHeight() - south.dom.content.bwrap.outerHeight();
        var top = south.dom.offset().top - south.dom.content.bwrap.outerHeight();
        center.setHeight(height);
        south.dom.offset({ top: top });
        if (west) {
            if (west.collapsed) {
                west.collDiv.height(height - 2 * (parseFloat(west.collDiv.css("borderBottomWidth")) || 0));
            }
            west.setHeight(height);
            EIAP.resize(west);
        }
        if (east) {
            if (east.collapsed) {
                east.collDiv.height(height - 2 * (parseFloat(east.collDiv.css("borderBottomWidth")) || 0));
            }
            east.setHeight(height);
            EIAP.resize(east);
        }
        south.collapsed = false;
        EIAP.resize(center);
    },

    resize: function () {
        var dom = this.scope.getDom();
        var parentWidth = dom.width();
        var parentHeight = dom.height();
        var centerWidth = parentWidth;
        var centerHeight = parentHeight;
        var parentPos = dom.offset();
        var height, width, panel, top = parentPos.top, left = parentPos.left, div;
        if (this.scope.north) {
            panel = EIAP.getCmp(this.scope.north);
            height = panel.height;
            if (panel.options.defaultHeight) {
                height = parseFloat(panel.options.defaultHeight) / 100;
                height = parseInt(parentHeight * height);
                panel.setHeight(height);
                panel.setWidth(parentWidth);
            }
            centerHeight -= (panel.dom.outerHeight() + panel.space);
            panel.dom.css({
                "position": "absolute"
            });
            top = panel.dom.outerHeight() + panel.dom.offset().top + panel.space;
            EIAP.resize(panel);
        }
        if (this.scope.south) {
            panel = EIAP.getCmp(this.scope.south);
            height = panel.height;
            if (panel.options.defaultHeight) {
                height = parseFloat(panel.options.defaultHeight) / 100;
                height = parseInt(parentHeight * height);
                panel.setHeight(height);
                panel.setWidth(parentWidth);
            }
            centerHeight -= (panel.dom.outerHeight() + panel.space);
            EIAP.resize(panel);
        }
        if (this.scope.west) {
            panel = EIAP.getCmp(this.scope.west);
            div = panel.collDiv;
            width = panel.width;
            panel.setHeight(centerHeight);
            if (panel.options.defaultWidth) {
                width = parseFloat(panel.options.defaultWidth) / 100;
                width = parseInt(parentWidth * width);
                panel.setWidth(width);
            }
            if (this.scope.north)
                panel.dom.offset({
                    top: top
                });
            if (div) {
                div.height(centerHeight - panel.space);
                if (this.scope.north)
                    div.offset({ top: top });
            }
            left = panel.width + panel.dom.offset().left + panel.space;
            if (panel.collapsed) {
                width = div.outerWidth();
                left = div.outerWidth() + div.offset().left + panel.space;
            }
            centerWidth -= (width + panel.space);
            EIAP.resize(panel);
        }
        if (this.scope.east) {
            panel = EIAP.getCmp(this.scope.east);
            div = panel.collDiv;
            width = panel.width;
            panel.setHeight(centerHeight);
            if (panel.options.defaultWidth) {
                width = parseFloat(panel.options.defaultWidth) / 100;
                width = parseInt(parentWidth * width);
                panel.setWidth(width);
            }
            if (div) {
                div.height(centerHeight - panel.space);
            }
            if (panel.collapsed) {
                width = div.outerWidth();
            }
            centerWidth -= (width + panel.space);
            EIAP.resize(panel);
        }
        if (this.scope.center) {
            panel = EIAP.getCmp(this.scope.center);
            panel.setHeight(centerHeight);
            panel.setWidth(centerWidth);
            if (this.scope.west)
                panel.dom.offset({
                    "left": left
                });
            if (this.scope.north)
                panel.dom.offset({
                    top: top
                });
            left += panel.width + panel.space;
            if (this.scope.east) {
                EIAP.getCmp(this.scope.east).dom.offset({
                    "left": left
                });
                if (this.scope.north)
                    EIAP.getCmp(this.scope.east).dom.offset({
                        "top": top
                    });
                div = EIAP.getCmp(this.scope.east).collDiv;
                if (div) {
                    div.offset({
                        "left": left
                    });
                    if (this.scope.north)
                        div.offset({
                            "top": top
                        });
                }
            }
            top += EIAP.getCmp(this.scope.center).dom.outerHeight() + panel.space;
            EIAP.resize(panel);
        }
        if (this.scope.south) {
            if (!this.scope.north) {
                top += 4;
            }
            EIAP.getCmp(this.scope.south).dom.offset({
                "top": top
            });
        }
    }
});﻿EIAP.FormLayout = function () {
    return new EIAP.layout.FormLayout(arguments[0], arguments[1]);
};

EIAP.layout.FormLayout = function () {
    this.scope = arguments[0];
    var type = arguments[1];
    if (type == "layout") {
        this.layout();
    } else if (type == "resize") {
        this.resize();
    }
};

EIAP.apply(EIAP.layout.FormLayout.prototype, {

    layout: function () {
        var items = this.scope.options.items, scope = this.scope;
        var dom = scope.getDom();
        var parentWidth = dom.width();
        parentWidth -= parseFloat(dom.css("marginLeft")) || 0;
        parentWidth -= parseFloat(dom.css("marginRight")) || 0;
        for (var i = 0; i < items.length; i++) {
            var item = items[i];
            var xtype = item.xtype ? item.xtype : scope.defaultType;
            var itemCellWidth = item.cellWidth;
            EIAP.applyIf(item, scope.defaultStyle);
            if (itemCellWidth) {
                item.cellWidth = itemCellWidth;
            }
            if (!xtype) {
                throw new Error(EIAP.error.noXtype);
            }
            var cmpFn = eval("EIAP." + xtype);
            if (!cmpFn) {
                throw new Error(EIAP.error.noXtype + ":" + "EIAP." + xtype);
            }
            var div = $("<div></div>");
            if (item.cellWidth) {
                div.addClass(scope.cellCss);
                if (item.cellWidth <= 1) {
                    div.width(parentWidth * item.cellWidth);
                } else {
                    div.width(item.cellWidth);
                }
            } else {
                div.addClass(scope.rowCss); //.width(parentWidth);
            }
            if (!item.renderTo) {
                var id = item.id || EIAP.getId(item.xtype);
                if (items.length > 1) {
                    div.append("<div id='" + id + "'>");
                } else {
                    div.remove();
                    div = $("<div id='" + id + "'>");
                }
                item.renderTo = id;
            }
            dom.append(div);
            item = cmpFn.call(cmpFn, item);
            scope.items.push(item.id);
        }
        if (dom[0].clientWidth != dom[0].offsetWidth) {
            EIAP.resize(scope);
        }
    },

    resize: function () {
        var items = this.scope.items;
        var dom = this.scope.getDom();
        var parentWidth = dom.width();
        parentWidth -= parseFloat(dom.css("marginLeft")) || 0;
        parentWidth -= parseFloat(dom.css("marginRight")) || 0;
        var isScrolled = dom[0].clientWidth != dom[0].offsetWidth;
        for (var i = 0; i < items.length; i++) {
            var item = EIAP.getCmp(items[i]);
            if (item.isDefined) {
                if (item.cellWidth) {
                    var column = item.dom.parent();
                    if (item.cellWidth <= 1) {
                        column.width(parentWidth * item.cellWidth);
                    } else {
                        column.width(item.cellWidth);
                    }
                } else {
                    var row = item.dom.parent();
                    if (isScrolled) {
                        row.width(parentWidth - 17);
                    } else {
                        row.width(parentWidth);
                    }
                }
            }
        }
    }
});﻿EIAP.ColumnLayout = function () {
    return new EIAP.layout.ColumnLayout(arguments[0], arguments[1]);
};

EIAP.layout.ColumnLayout = function () {
    this.scope = arguments[0];
    var type = arguments[1];
    if (type == "layout") {
        this.layout();
    } else if (type == "resize") {
        this.resize();
    }
};

EIAP.apply(EIAP.layout.ColumnLayout.prototype, {

    layout: function () {
        var items = this.scope.options.items, g = this, scope = this.scope;
        var dom = scope.getDom();
        var totalLength = 0;
        var parentWidth = dom.width(), parentHeight = dom.height();
        parentWidth -= parseFloat(dom.css("marginLeft")) || 0;
        parentWidth -= parseFloat(dom.css("marginRight")) || 0;
        parentHeight -= parseFloat(dom.css("marginTop")) || 0;
        parentHeight -= parseFloat(dom.css("marginButtom")) || 0;
        for (var i = 0; i < items.length; i++) {
            var item = items[i], id;
            var xtype = item.xtype ? item.xtype : scope.defaultType;
            if (!item.width)
                EIAP.applyIf(item, scope.defaultStyle);
            if (!xtype) {
                throw new Error(EIAP.error.noXtype);
            }
            var cmpFn = eval("EIAP." + xtype);
            if (!cmpFn) {
                throw new Error(EIAP.error.noXtype + ":" + "EIAP." + xtype);
            }
            var div = $("<div></div>");
            if (item.columnWidth && !item.hidden) {
                div.addClass(scope.columnCss);
                if (item.columnWidth <= 1) {
                    div.width(parentWidth * item.columnWidth);
                } else {
                    div.width(item.columnWidth);
                }
                div.height(parentHeight);
                if (!item.renderTo) {
                    id = item.id || EIAP.getId(item.xtype);
                    div.append($("<div id='" + id + "'>"));
                    item.renderTo = id;
                }
            } else {
                div.addClass(scope.rowCss);
                div.width(parentWidth);
                div.height(parentHeight);
                if (!item.renderTo) {
                    id = item.id || EIAP.getId(item.xtype);
                    div.append($("<div id='" + id + "'>"));
                    item.renderTo = id;
                }
            }
            dom.append(div);
            item = cmpFn.call(cmpFn, item);
            scope.items.push(item.id);
        }
    },

    resize: function () {
        var items = this.scope.items;
        var dom = this.scope.getDom();
        var parentWidth = dom.width(), parentHeight = dom.height();
        parentWidth -= parseFloat(dom.css("marginLeft")) || 0;
        parentWidth -= parseFloat(dom.css("marginRight")) || 0;
        parentHeight -= parseFloat(dom.css("marginTop")) || 0;
        parentHeight -= parseFloat(dom.css("marginButtom")) || 0;
        for (var i = 0; i < items.length; i++) {
            var item = EIAP.getCmp(items[i]);
            if (item.isDefined) {
                if (item.columnWidth && !item.hidden) {
                    var column = item.dom.parent();
                    if (item.columnWidth <= 1) {
                        column.width(parentWidth * item.columnWidth);
                    } else {
                        column.width(item.columnWidth);
                    }
                    column.height(parentHeight);
                } else {
                    var row = item.dom.parent();
                    row.width(parentWidth);
                    row.height(parentHeight);
                }
            }
        }
    }
});﻿EIAP.AccordionLayout = function () {
    return new EIAP.layout.AccordionLayout(arguments[0], arguments[1]);
};

EIAP.layout.AccordionLayout = function () {
    this.scope = arguments[0];
    var type = arguments[1];
    if (type == "layout") {
        this.layout();
    } else if (type == "resize") {
        this.resize();
    }
};

EIAP.apply(EIAP.layout.AccordionLayout.prototype, {
    itemCss: "ux-accordion-item",
    headerCss: "ux-accordion-header",
    toolCss: "ux-accordion-tool",
    toggleCss: "ux-accordion-toggle",
    collapsedCss: "ux-accordion-collapsed",
    layout: function () {
        var items = this.scope.options.items, g = this, scope = this.scope;
        var dom = scope.getDom();
        var height = dom.height() - 23 * items.length + 1;
        g.initHeight = height;
        var froceSetting = { height: height };
        var defaultSetting = { border: true, async: true, xtype: "Panel" };
        for (var i = 0; i < items.length; i++) {
            var item = items[i];
            item.index = i;
            EIAP.apply(item, froceSetting);
            EIAP.applyIf(item, scope.defaultStyle);
            item.xtype = item.xtype ? item.xtype : scope.defaultType;
            EIAP.applyIf(item, defaultSetting);
            if (!item.xtype) {
                throw new Error(EIAP.error.noXtype);
            }
            //初始化header
            g.initDom(item);
            //清除Panel中相关属性的影响
            delete item.title;
            delete item.iconCls;
            delete item.collapsible;

            var cmp = eval("EIAP." + item.xtype);
            if (!cmp) {
                throw new Error(String.format(EIAP.error.noCmp, item.xtype));
            }
            if (item.actived || !item.async) {
                cmp = cmp.call(cmp, item);
                scope.items.push(cmp.id);
                if (item.actived) {
                    scope.accActived = { dom: cmp.dom, index: i, id: item.renderTo };
                }
                cmp.dom.hide();
            }
        }
        if (scope.accActived)
            scope.accActived.dom.show();
        else {
            g.active(0);
        }
    },

    initDom: function (item) {
        var g = this, scope = g.scope, dom = scope.getDom();
        var div = $("<div></div>").addClass(g.itemCss);
        var header = $("<div></div>").addClass(g.headerCss);
        header.append($("<div></div>").addClass(g.toolCss).addClass(g.toggleCss));
        if (item.index == 0) {
            header.css({ "border-top-width": 0 });
        }
        header.append("<span>" + item.title + "</span>");
        div.append(header);
        var id = EIAP.getId(item.xtype);
        item.renderTo = id;
        header.attr("eiapid", id);
        div.append("<div id='" + id + "'></div>");
        dom.append(div);

        header.bind("click", function () {
            g.active($(arguments[0].currentTarget).attr("eiapid"));
        });
    },
    active: function () {
        var g = this, scope = g.scope, items = scope.options.items;
        var id, index = 0, cmp, flag = false;
        if (scope.accActived) {
            if (scope.accActived.index == arguments[0] || scope.accActived.id == arguments[0]) {
                return;
            }
            var dom = scope.accActived.dom;
            $(dom.prev().children()[0]).removeClass(g.collapsedCss).addClass(g.toggleCss);
            dom.hide();
        }
        if (typeof arguments[0] == "string") {
            id = arguments[0];
            cmp = EIAP.getCmp(id);
            if (!cmp) {
                for (var i = 0; i < items.length; i++) {
                    var item = items[i];
                    if (item.renderTo == id || item.id == id) {
                        index = i;
                    }
                }
            }
        } else if (typeof arguments[0] == "number") {
            index = arguments[0];
        }
        id = items[index].id || items[index].renderTo;
        cmp = cmp || EIAP.getCmp(id);
        if (!cmp) {
            var fn = eval("EIAP." + items[index].xtype);
            cmp = fn.call(fn, items[index]);
        }
        cmp.dom.show();
        $(cmp.dom.prev().children()[0]).addClass(g.collapsedCss).removeClass(g.toggleCss);
        scope.accActived = { dom: cmp.dom, index: index, id: cmp.renderTo };
        if (scope.accActive) {
            scope.accActive(cmp);
        }
    },
    resize: function () {
        var g = this, scope = g.scope, items = scope.options.items;
        var dom = scope.getDom();
        var height = dom.height() - 23 * items.length;
        scope.accActived.dom.hide();
        if (typeof scope.width == "string" && scope.width.indexOf("%") > -1) {
            scope.setWidth(scope.width);
        }
        scope.accActived.dom.show();
        for (var i = 0; i < items.length; i++) {
            var item = items[i];
            var id = item.id || item.renderTo;
            var cmp = EIAP.getCmp(id);
            if (!cmp) {
                item.height = height;
            } else {
                cmp.setHeight(height);
                EIAP.resize(cmp);
            }
        }
    }
});﻿EIAP.AutoLayout = function () {
    return new EIAP.layout.AutoLayout(arguments[0], arguments[1]);
};

EIAP.layout.AutoLayout = function () {
    this.scope = arguments[0];
    var type = arguments[1];
    if (type == "layout") {
        this.layout();
    } else if (type == "resize") {
        this.resize();
    }
};

EIAP.apply(EIAP.layout.AutoLayout.prototype, {
    floatCss: "ux-layout-auto",
    layout: function () {
        var items = this.scope.options.items, g = this, scope = this.scope;
        var dom = scope.getDom();
        for (var i = 0; i < items.length; i++) {
            var item = items[i];
            var config = {
                parentCmp: scope.id || scope.renderTo,
                isDefined: true
            };
            EIAP.applyIf(item, config);
            var xtype = item.xtype ? item.xtype : scope.defaultType;
            EIAP.applyIf(item, scope.defaultStyle);
            if (!item.renderTo) {
                var id = item.id || EIAP.getId(item.xtype);
                dom.append("<div id='" + id + "' style='float:left;padding-left:" + scope.space + "px'>");
                item.renderTo = id;
            }
            if (!xtype) {
                throw new Error(EIAP.error.noXtype);
            }
            var cmpFn = eval("EIAP." + xtype);
            if (!cmpFn) {
                throw new Error(EIAP.error.noXtype + ":" + "EIAP." + xtype);
            }
            item = cmpFn.call(cmpFn, item);
            scope.items.push(item.id);
        }
    },

    resize: function () {

    }
});﻿EIAP.Tab = function () {
    return new EIAP.tab.Tab(arguments[0]);
};
EIAP.tab.Tab = $.fn.eiapTab = EIAP.extend(EIAP.UIComponent, {
    height: "100%",
    width: "100%",
    heightDiff: 0, // 高度补差
    changeHeightOnResize: true,
    contextmenu: false,
    showTabMenu: false,
    dblClickToClose: false, // 是否双击时关闭
    dragToMove: false, // 是否允许拖动时改变tab项的位置
    onBeforeOverrideTabItem: null,
    onAfterOverrideTabItem: null,
    onBeforeRemoveTabItem: null,
    onAfterRemoveTabItem: null,
    onBeforeAddTabItem: null,
    onAfterAddTabItem: null,
    onBeforeSetTabItemActived: null,
    onAfterSetTabItemActived: null,
    initComponent: function () {
        EIAP.tab.Tab.superclass.initComponent.call(this);
    },
    __getType: function () {
        return 'Tab';
    },
    __idPrev: function () {
        return 'Tab';
    },
    _extMethods: function () {
        return EIAP.tab.Tab;
    },
    _render: function () {
        var g = this;
        g.tab = $(this.element);
        g.tab.addClass("ux-tab");
        if (g.contextmenu && EIAP.menu.Menu) {
            g.tab.menu = EIAP.Menu({
                items: [{
                    title: g.closeText,
                    id: 'close',
                    iconCls: 'icon-close',
                    handler: function () {
                        g._menuItemClick.apply(g, arguments);
                    }
                }, '-', {
                    title: g.closeOtherText,
                    id: 'closeother',
                    iconCls: 'icon-closeother',
                    handler: function () {
                        g._menuItemClick.apply(g, arguments);
                    }
                }, {
                    title: g.closeAllText,
                    id: 'closeall',
                    iconCls: 'icon-closeall',
                    handler: function () {
                        g._menuItemClick.apply(g, arguments);
                    }
                }, {
                    title: g.reloadText,
                    id: 'reload',
                    iconCls: 'icon-pagerefresh',
                    handler: function () {
                        g._menuItemClick.apply(g, arguments);
                    }
                }]
            });
        };
        g.tab.content = $('<div class="ux-tab-content"></div>');
        $("> div", g.tab).appendTo(g.tab.content);
        g.tab.content.appendTo(g.tab);
        g.tab.links = $('<div class="ux-tab-links"><ul style="left: 0px; "></ul></div>');
        g.tab.links.prependTo(g.tab);
        g.tab.links.ul = $("ul", g.tab.links);
        var activeds = $("> div[actived=true]", g.tab.content);
        var actived = activeds.length > 0;
        g.activeTabId = activeds.attr("id");
        $("> div", g.tab.content).each(function (i) {
            var li = $('<li class=""><a></a><div class="ux-tab-links-item-left"></div><div class="ux-tab-links-item-right"></div></li>');
            var contentitem = $(this), tabtitle = contentitem.attr("title")
					|| "newTab" + i;
            $("> a", li).html('<span class="ux-tab-icon"></span>' + tabtitle);
            var tabid = contentitem.attr("id");
            if (tabid == undefined) {
                tabid = g.getNewTabid();
                contentitem.attr("tabid", tabid);
                if (contentitem.attr("actived")) {
                    g.activeTabId = tabid;
                }
            }
            li.attr("tabid", tabid);
            if (!actived && i == 0)
                g.activeTabId = tabid;
            var showClose = contentitem.attr("showClose");
            if (showClose) {
                li.append("<div class='ux-tab-links-item-close'></div>");
            }
            var tabicon = contentitem.attr("iconCls");
            if (tabicon) {
                $(".ux-tab-icon", li).addClass(tabicon).show();
            }
            $("> ul", g.tab.links).append(li);
            if (!contentitem.hasClass("ux-tab-content-item"))
                contentitem.addClass("ux-tab-content-item");
            var url = contentitem.attr("url");
            if (url) {
                var iframe = $("iframe:first", contentitem);
                if (iframe.length <= 0) {
                    iframe = $('"<iframe frameborder="0" width="100%" height="100%"></iframe>"');
                    contentitem.append(iframe);
                }
                iframe.attr("name", tabid).attr("src", url);
                if (iframe[0].readyState != "complete") {
                    if (contentitem.find(".ux-tab-loading:first").length == 0)
                        contentitem
								.prepend("<div class='ux-tab-loading' style='display:block;'></div>");
                    var iframeloading = $(".ux-tab-loading:first", contentitem);
                    iframe.bind('load.tab', function () {
                        iframeloading.hide();
                    });
                }
            }
            
        });
        if (g.showTabMenu && EIAP.menu.Menu) {
            g.setTabMenuButton();
        }
        g.setTabButton();
        // init
        if (g.tab.parent()[0].tagName.toLowerCase() == "body") {
            g.tab.parent().addClass("ux-tab-bg");
        } else {
            g.tab.addClass("ux-tab-bg").css("border-width", 0);
        }
        g.onResize();
        g.setTabItemActived(g.activeTabId);
        // add even
        $("li", g.tab.links).each(function () {
            g._addTabItemEvent($(this));
        });
        g.tab.bind('dblclick.tab', function (e) {
            if (!g.dblClickToClose)
                return;
            g.dblclicking = true;
            var obj = (e.target || e.srcElement);
            var tagName = obj.tagName.toLowerCase();
            if (tagName == "a") {
                var tabid = $(obj).parent().attr("tabid");
                var allowClose = $(obj).parent()
								.find("div.ux-tab-links-item-close").length
								? true
								: false;
                if (allowClose) {
                    g.removeTabItem(tabid);
                }
            }
            g.dblclicking = false;
        });
        g.set(g);
    },
    _applyDrag: function (tabItemDom) {
        var g = this;
        g.droptip = g.droptip
				|| $("<div class='ux-tab-drag-droptip' style='display:none'><div class='ux-drop-move-up'></div><div class='ux-drop-move-down'></div></div>")
						.appendTo('body');
        var drag = $(tabItemDom).eiapDrag({
            revert: true,
            animate: false,
            proxy: function () {
                var name = $(this).find("a").html();
                g.dragproxy = $("<div class='ux-tab-drag-proxy' style='display:none'><div class='ux-drop-icon ux-drop-no'></div></div>")
						.appendTo('body');
                g.dragproxy.append(name);
                return g.dragproxy;
            },
            onRendered: function () {
                this.set('cursor', 'pointer');
            },
            onStartDrag: function (current, e) {
                if (!$(tabItemDom).hasClass("ux-actived"))
                    return false;
                if (e.button == 2)
                    return false;
                var obj = e.srcElement || e.target;
                if ($(obj).hasClass("ux-tab-links-item-close"))
                    return false;
            },
            onDrag: function (current, e) {
                if (g.dropIn == null)
                    g.dropIn = -1;
                var tabItems = g.tab.links.ul.find('>li');
                var targetIndex = tabItems.index(current.target);
                tabItems.each(function (i) {
                    if (targetIndex == i) {
                        return;
                    }
                    var isAfter = i > targetIndex;
                    if (g.dropIn != -1 && g.dropIn != i)
                        return;
                    var offset = $(this).offset();
                    var range = {
                        top: offset.top,
                        bottom: offset.top + $(this).height(),
                        left: offset.left - 10,
                        right: offset.left + 10
                    };
                    if (isAfter) {
                        range.left += $(this).width();
                        range.right += $(this).width();
                    }
                    var pageX = e.pageX || e.screenX;
                    var pageY = e.pageY || e.screenY;
                    if (pageX > range.left && pageX < range.right
									&& pageY > range.top
									&& pageY < range.bottom) {
                        g.droptip.css({
                            left: range.left + 5,
                            top: range.top - 9
                        }).show();
                        g.dropIn = i;
                        g.dragproxy.find(".ux-drop-icon")
										.removeClass("ux-drop-no")
										.addClass("ux-drop-yes");
                    } else {
                        g.dropIn = -1;
                        g.droptip.hide();
                        g.dragproxy.find(".ux-drop-icon")
										.removeClass("ux-drop-yes")
										.addClass("ux-drop-no");
                    }
                });
            },
            onStopDrag: function (current, e) {
                if (g.dropIn > -1) {
                    var to = g.tab.links.ul.find('>li:eq(' + g.dropIn + ')')
							.attr("tabid");
                    var from = $(current.target).attr("tabid");
                    setTimeout(function () {
                        g.moveTabItem(from, to);
                    }, 0);
                    g.dropIn = -1;
                    g.dragproxy.remove();
                }
                g.droptip.hide();
                this.set('cursor', 'default');
            }
        });
        return drag;
    },
    _setDragToMove: function (value) {
        if (!$.fn.eiapDrag)
            return;
        var g = this;
        if (value) {
            if (g.drags)
                return;
            g.drags = g.drags || [];
            g.tab.links.ul.find('>li').each(function () {
                g.drags.push(g._applyDrag(this));
            });
        }
    },
    moveTabItem: function (fromTabItemId, toTabItemId) {
        var g = this;
        var from = g.tab.links.ul.find('>li[tabid="' + fromTabItemId + '"]');
        var to = g.tab.links.ul.find('>li[tabid="' + toTabItemId + '"]');
        var index1 = g.tab.links.ul.find(">li").index(from);
        var index2 = g.tab.links.ul.find(">li").index(to);
        if (index1 < index2) {
            to.after(from);
        } else {
            to.before(from);
        }
    },
    // 设置tab按钮(左和右),显示返回true,隐藏返回false
    setTabButton: function () {
        var g = this;
        var sumwidth = 0;
        $("li", g.tab.links.ul).each(function () {
            sumwidth += $(this).width() + 2;
        });
        var mainwidth = g.tab.width();
        if (sumwidth > mainwidth) {
            g.tab.links
					.append('<div class="ux-tab-links-left"></div><div class="ux-tab-links-right"></div>');
            g.setTabButtonEven();
            if (!g.showTabMenu) {
                $(".ux-tab-links-left", g.tab.links).css("right", 17);
                $(".ux-tab-links-right", g.tab.links).css("right", 0);
            }
            return true;
        } else {
            g.tab.links.ul.animate({
                left: 0
            });
            $(".ux-tab-links-left .ux-tab-links-right", g.tab.links).remove();
            return false;
        }
    },
    // 设置左右按钮的事件 标签超出最大宽度时，可左右拖动
    setTabButtonEven: function () {
        var g = this;
        $(".ux-tab-links-left", g.tab.links).hover(function () {
            $(this).addClass("ux-tab-links-left-over");
        }, function () {
            $(this).removeClass("ux-tab-links-left-over");
        }).click(function () {
            g.moveToPrevTabItem();
        });
        $(".ux-tab-links-right", g.tab.links).hover(function () {
            $(this).addClass("ux-tab-links-right-over");
        }, function () {
            $(this).removeClass("ux-tab-links-right-over");
        }).click(function () {
            g.moveToNextTabItem();
        });
    },
    setTabMenuButton: function () {
        var g = this;
        g.tab.links.append('<div class="ux-tab-links-menu"></div>');
        g._addTabMenusButton();
        g.setTabMenuButtonEven();
    },
    setTabMenuButtonEven: function () {
        var g = this;
        $(".ux-tab-links-menu", g.tab.links).hover(function () {
            $(this).addClass("ux-tab-links-menu-over");
        }, function () {
            $(this).removeClass("ux-tab-links-menu-over");
        }).click(function (e) {
            if (!g.tab.tabMenu)
                return;
            g.tab.tabMenu.show({
                top: $(this).offset().top + 23,
                left: $(this).offset().left - 140
            });
            return false;
        });
    },
    _addTabMenusButton: function () {
        var g = this;
        if (arguments.length != 0 && g.tab.tabMenu) {
            var cfg = arguments[0];
            var menu = [{
                title: cfg.title || cfg.id,
                id: cfg.id,
                iconCls: cfg.iconCls || "",
                handler: function () {
                    g._tabMenuItemClick.apply(g, arguments);
                }
            }];
            g.tab.tabMenu.addItems(menu, g.tab.tabMenu);
        } else {
            g.tabMenus = [];
            $("> li", g.tab.links.ul).each(function () {
                var tabid = $(this).attr("tabid");
                g.tabMenus.push({
                    title: $('#' + tabid).attr("title"),
                    id: tabid,
                    iconCls: $('#' + tabid).attr("iconcls"),
                    handler: function () {
                        g._tabMenuItemClick.apply(g, arguments);
                    }
                });
            });
            if (g.tabMenus.length > 0) {
                g.tab.tabMenu = EIAP.Menu({
                    items: g.tabMenus
                });
            }
        }
    },
    _removeTabMenusButton: function () {
        var g = this;
        if (arguments.length != 0 && g.tab.tabMenu) {
            var tabid = arguments[0];
            g.tab.tabMenu.removeItem(tabid);
        }
    },
    // 切换到上一个tab
    moveToPrevTabItem: function () {
        var g = this, num = 1;
        var btnWitdth = 0;
        var leftList = new Array(); // 记录每个tab的left,由左到右
        var tabItems = $("li", g.tab.links.ul);
        $(".ux-tab-links-right", g.tab)
				.removeClass("ux-tab-links-right-invalid");
        tabItems.each(function (i) {
            var currentItemLeft = -1 * btnWitdth;
            if (i > 0) {
                currentItemLeft = parseInt(leftList[i - 1])
								+ $(this).prev().width() + 2;
            }
            leftList.push(currentItemLeft);
        });
        var currentLeft = -1 * parseInt(g.tab.links.ul.css("left"));
        for (var i = 0; i < leftList.length - 1; i++) {
            if (leftList[i] < currentLeft && leftList[i + 1] >= currentLeft) {
                g.tab.links.ul.animate({
                    left: -1 * parseInt(leftList[i])
                });
                return;
            } else {
                num++;
            }
        }
        if (tabItems.length == num) {
            $(".ux-tab-links-left", g.tab)
					.addClass("ux-tab-links-left-invalid");
        }
    },
    // 切换到下一个tab
    moveToNextTabItem: function () {
        var g = this, num = 1;
        var btnWitdth = $(".ux-tab-links-right", g.tab).width()
				+ $(".ux-tab-links-left", g.tab).width();
        if ($(".ux-tab-links-menu", g.tab).length > 0) {
            btnWitdth += $(".ux-tab-links-menu", g.tab).width();
        }
        var sumwidth = 0;
        var tabItems = $("li", g.tab.links.ul);
        $(".ux-tab-links-left", g.tab).removeClass("ux-tab-links-left-invalid");
        tabItems.each(function () {
            sumwidth += $(this).width() + 2;
        });
        var mainwidth = g.tab.width();
        var leftList = new Array(); // 记录每个tab的left,由右到左
        for (var i = tabItems.length - 1; i >= 0; i--) {
            var currentItemLeft = sumwidth - mainwidth + btnWitdth + 6;
            if (i != tabItems.length - 1) {
                currentItemLeft = parseInt(leftList[tabItems.length - 2 - i])
						- $(tabItems[i + 1]).width() - 2;
            }
            leftList.push(currentItemLeft);
        }
        var currentLeft = -1 * parseInt(g.tab.links.ul.css("left"));
        for (var j = 1; j < leftList.length; j++) {
            if (leftList[j] <= currentLeft && leftList[j - 1] > currentLeft) {
                var left = -1 * parseInt(leftList[j - 1]);
                g.tab.links.ul.animate({
                    left: left
                });
                return;
            } else {
                num++;
            }
        }
        if (tabItems.length == num) {
            $(".ux-tab-links-right", g.tab)
					.addClass("ux-tab-links-right-invalid");
        }
    },
    getTabItemCount: function () {
        var g = this;
        return $("li", g.tab.links.ul).length;
    },
    getActivedTabItemID: function () {
        var g = this;
        return $("li.ux-actived", g.tab.links.ul).attr("tabid");
    },
    removeActivedTabItem: function () {
        var g = this;
        g.removeTabItem(g.getActivedTabItemID());
    },
    // 覆盖选择的tabitem
    overrideActivedTabItem: function (options) {
        var g = this;
        g.overrideTabItem(g.getActivedTabItemID(), options);
    },
    // 覆盖
    overrideTabItem: function (targettabid, options) {
        var g = this;
        if (g.trigger('beforeOverrideTabItem', [targettabid]) == false)
            return false;
        var tabid = options.tabid;
        if (tabid == undefined)
            tabid = g.getNewTabid();
        var url = options.url;
        var content = options.content;
        var title = options.title || tabid;
        var showClose = options.showClose;
        var height = options.height;
        // 如果已经存在
        if (g.isTabItemExist(tabid)) {
            return;
        }
        var tabitem = $('li[tabid="' + targettabid + '"]', g.tab.links.ul);
        var contentitem = $(
				'.ux-tab-content-item[tabid="' + targettabid + '"]',
				g.tab.content);
        if (!tabitem || !contentitem)
            return;
        tabitem.attr("tabid", tabid);
        contentitem.attr("tabid", tabid);
        if ($("iframe", contentitem).length == 0 && url) {
            contentitem.html("<iframe frameborder='0'></iframe>");
        } else if (content) {
            contentitem.html(content);
        }
        $("iframe", contentitem).attr("name", tabid);
        if (showClose == undefined)
            showClose = true;
        if (showClose == false)
            $(".ux-tab-links-item-close", tabitem).remove();
        else {
            if ($(".ux-tab-links-item-close", tabitem).length == 0)
                tabitem.append("<div class='ux-tab-links-item-close'></div>");
        }
        if (height)
            contentitem.height(height);
        $("a", tabitem).text(title);
        $("iframe", contentitem).attr("src", url);
        g.trigger('afterOverrideTabItem', [targettabid]);
    },
    // 选中tab项
    setTabItemActived: function (tabid) {
        var g = this;
        if (g.trigger('beforeSetTabItemActived', [tabid]) == false)
            return false;
        g.activeTabId = tabid;
        $('> .ux-tab-content-item[id="' + tabid + '"]', g.tab.content).show()
				.siblings().hide();
        $('li[tabid="' + tabid + '"]', g.tab.links.ul).addClass("ux-actived")
				.siblings().removeClass("ux-actived");
        g.trigger('afterSetTabItemActived', [tabid]);
        g.moveToTabItem(tabid);
    },
    // 如果指定的tab在面板中不可见时，则向左或向右移动tab以显示tab
    moveToTabItem: function (tabid) {
        var g = this;
        var sumwidth = 0;
        $("li", g.tab.links.ul).each(function () {
            sumwidth += $(this).width() + 2;
        });
        var mainwidth = g.tab.width(), itempos = [], curitemleft = 0;
        var btnWitdth = $(".ux-tab-links-right", g.tab).width()
				+ $(".ux-tab-links-left", g.tab).width();
        if ($(".ux-tab-links-menu", g.tab).length > 0) {
            btnWitdth += $(".ux-tab-links-menu", g.tab).width();
        }
        if (sumwidth > mainwidth) {
            $("li", g.tab.links.ul).each(function (i) {
                if (i > 0) {
                    curitemleft = parseInt(itempos[i - 1].left)
							+ $(this).prev().width() + 2;
                }
                itempos.push({
                    tabid: $(this).attr("tabid"),
                    left: curitemleft
                });
            });
            for (var m = 0; m < itempos.length; m++) {
                if (itempos[m].tabid == tabid) {
                    var diff = itempos[m].left - mainwidth;
                    if (diff > 0) {
                        g.tab.links.ul.animate({
                            left: (diff + ($(
											'li[tabid="' + tabid + '"]',
											g.tab.links.ul).width()
											+ btnWitdth + 2))
											* -1
                        });
                    } else {
                        g.tab.links.ul.animate({
                            left: -1 * parseInt(itempos[m].left)
                        });
                    }
                    return false;
                }
            }
        }
    },
    // 移动到最后一个tab
    moveToLastTabItem: function () {
        var g = this;
        var sumwidth = 0;
        $("li", g.tab.links.ul).each(function () {
            sumwidth += $(this).width() + 2;
        });
        var mainwidth = g.tab.width();
        if (sumwidth > mainwidth) {
            var btnWitdth = $(".ux-tab-links-right", g.tab.links).width()
					+ $(".ux-tab-links-left", g.tab.links).width();
            if ($(".ux-tab-links-menu", g.tab).length > 0)
                btnWitdth += $(".ux-tab-links-menu", g.tab).width();
            g.tab.links.ul.animate({
                left: -1 * (sumwidth - mainwidth + btnWitdth + 2)
            });
        }
    },
    // 判断tab是否存在
    isTabItemExist: function (tabid) {
        var g = this;
        return $('li[tabid="' + tabid + '"]', g.tab.links.ul).length > 0;
    },
    // 增加一个tab
    addTabItem: function () {
        var g = this;
        if (g.trigger('beforeAddTabItem', [tabid]) == false)
            return false;
        var cfg = {
            id: g.getNewTabid(),
            title: '',
            url: '',
            content: '',
            showClose: true,
            height: 0,
            callback: null
        };
        cfg = $.extend(cfg, arguments[0] || {});
        var tabid = cfg.id;
        var title = cfg.title || tabid;
        // 如果已经存在
        if (g.isTabItemExist(tabid)) {
            g.setTabItemActived(tabid);
            return;
        }
        var tabitem = $("<li><a></a><div class='ux-tab-links-item-left'></div><div class='ux-tab-links-item-right'></div><div class='ux-tab-links-item-close'></div></li>");
        var contentitem = $("<div class='ux-tab-content-item'><div class='ux-tab-loading' style='display:block;'></div><iframe frameborder='0' height='100%' width='100%'></iframe></div>");
        var iframeloading = $("div:first", contentitem);
        var iframe = $("iframe:first", contentitem);
        tabitem.attr("tabid", tabid);
        contentitem.attr("id", tabid);
        if (cfg.url) {
            iframe.attr("name", tabid).attr("id", tabid).attr("src", cfg.url)
					.bind('load.tab', function () {
					    iframeloading.hide();
					    if (cfg.callback)
					        cfg.callback();
					});
            iframe.height(g.tab.content.height());
        } else {
            iframe.remove();
            iframeloading.remove();
        }
        if (cfg.content) {
            contentitem.html(cfg.content);
        }
        if (cfg.showClose == false)
            $(".ux-tab-links-item-close", tabitem).remove();
        if (cfg.height)
            contentitem.height(cfg.height);
        $("> a", tabitem).html('<span class="ux-tab-icon"></span>' + title);
        var tabicon = cfg.iconCls;
        if (tabicon) {
            $(".ux-tab-icon", tabitem).addClass(tabicon).show();
        }
        g.tab.links.ul.append(tabitem);
        g.tab.content.append(contentitem);
        g.onResize();
        g.setTabItemActived(tabid);
        if (g.setTabButton()) {
            g.moveToLastTabItem();
        }
        if (g.tab.tabMenu) {
            g._addTabMenusButton(cfg);
        }
        // 增加事件
        g._addTabItemEvent(tabitem);
        if (g.dragToMove && $.fn.eiapDrag) {
            g.drags = g.drags || [];
            tabitem.each(function () {
                g.drags.push(g._applyDrag(this));
            });
        }
        g.trigger('afterAddTabItem', [tabid]);
    },
    _addTabItemEvent: function (tabitem) {
        var g = this;
        tabitem.click(function () {
            var tabid = $(this).attr("tabid");
            g.setTabItemActived(tabid);
        });
        // 右键事件支持
        g.tab.menu && g._addTabItemContextMenuEven(tabitem);
        $(".ux-tab-links-item-close", tabitem).hover(function () {
            $(this).addClass("ux-tab-links-item-close-over");
        }, function () {
            $(this).removeClass("ux-tab-links-item-close-over");
        }).click(function () {
            var tabid = $(this).parent().attr("tabid");
            g.removeTabItem(tabid);
        });

    },
    // 移除tab项
    removeTabItem: function (tabid) {
        var g = this;
        g._removeTabMenusButton(tabid);
        if (g.trigger('beforeRemoveTabItem', [tabid]) == false)
            return false;
        var currentIsActived = $('li[tabid="' + tabid + '"]', g.tab.links.ul)
				.hasClass("ux-actived");
        if (currentIsActived) {
            $('.ux-tab-content-item[id="' + tabid + '"]', g.tab.content).prev()
					.show();
            $('li[tabid="' + tabid + '"]', g.tab.links.ul).prev()
					.addClass("ux-actived").siblings()
					.removeClass("ux-actived");
        }
        $('.ux-tab-content-item[id="' + tabid + '"]', g.tab.content).remove();
        $('li[tabid="' + tabid + '"]', g.tab.links.ul).remove();
        g.setTabButton();
        g.trigger('afterRemoveTabItem', [tabid]);
        EIAP.remove(tabid);
    },
    getNewTabid: function () {
        var g = this;
        g.getnewidcount = g.getnewidcount || 0;
        return 'tabitem' + (++g.getnewidcount);
    },
    // notabid 过滤掉tabid的
    // noclose 过滤掉没有关闭按钮的
    getTabidList: function (notabid, noclose) {
        var g = this;
        var tabidlist = [];
        $("> li", g.tab.links.ul).each(function () {
            if ($(this).attr("tabid")
					&& $(this).attr("tabid") != notabid
					&& (!noclose || $(".ux-tab-links-item-close", this).length > 0)) {
                tabidlist.push($(this).attr("tabid"));
            }
        });
        return tabidlist;
    },
    removeOther: function (tabid, compel) {
        var g = this;
        var tabidlist = g.getTabidList(tabid, true);
        $(tabidlist).each(function () {
            g.removeTabItem(this);
        });
    },
    reload: function (tabid) {
        var g = this;
        var contentitem = $('.ux-tab-content-item[id="' + tabid + '"]');
        var iframeloading = $(".ux-tab-loading:first", contentitem);
        var iframe = $("iframe:first", contentitem);
        var url = $(iframe).attr("src");
        iframeloading.show();
        iframe.attr("src", url).unbind('load.tab').bind('load.tab', function () {
            iframeloading.hide();
        });
    },
    removeAll: function (compel) {
        var g = this;
        var tabidlist = g.getTabidList(null, true);
        $(tabidlist).each(function () {
            g.removeTabItem(this);
        });
    },
    onResize: function () {
        var g = this, pheight = 0, pwidth = 0;
        if (typeof g.height != "string" && g.height.indexOf("%") < 0) {
            pheight = g.height;
        }
        if (typeof g.width != "string" && g.width.indexOf("%") < 0) {
            pwidth = g.width;
        }
        var parentDom = g.tab.parent();
        if (parentDom[0].tagName.toLowerCase() == "body") {
            if (pheight == 0) {
                pheight = $(window).height();
                pheight -= parseInt($('body').css('paddingTop')) || 0;
                pheight -= parseInt($('body').css('paddingBottom')) || 0;
                pheight = g.heightDiff + pheight * parseFloat(g.height) * 0.01;
                $('body').css({ "overflow": "hidden" });
                $('html').css({ "overflow": "hidden" });
            }
            if (pwidth == 0) {
                pwidth = $(window).width();
                pwidth -= parseInt($('body').css('paddingLeft')) || 0;
                pwidth -= parseInt($('body').css('paddingRight')) || 0;
            }
        } else {
            if (pheight == 0) {
                pheight = g.heightDiff
                    + (parentDom.height() * parseFloat(g.height) * 0.01);
            }
            if (pwidth == 0) {
                pwidth = parentDom.width();
                pwidth -= parseInt(parentDom.css('paddingLeft')) || 0;
                pwidth -= parseInt(parentDom.css('paddingRight')) || 0;
            }
        }
        pheight -= parseInt(g.tab.css('borderTopWidth')) || 0;
        pheight -= parseInt(g.tab.css('borderBottomWidth')) || 0;
        pwidth -= parseInt(g.tab.css('borderLeftWidth')) || 0;
        pwidth -= parseInt(g.tab.css('borderRightWidth')) || 0;
        g.tab.height(pheight);
        g.tab.width(pwidth);
        pheight = pheight - g.tab.links.height();
        pheight -= parseInt(g.tab.links.css('borderTopWidth')) || 0;
        pheight -= parseInt(g.tab.links.css('borderBottomWidth')) || 0;
        g.tab.content.width(pwidth).height(pheight);
        $("> .ux-tab-content-item", g.tab.content).width(pwidth).height(pheight);
    },
    _menuItemClick: function (item) {
        var g = this;
        if (!item.id || !g.actionTabid)
            return;
        switch (item.id) {
            case "close":
                g.removeTabItem(g.actionTabid);
                g.actionTabid = null;
                break;
            case "closeother":
                g.removeOther(g.actionTabid);
                break;
            case "closeall":
                g.removeAll();
                g.actionTabid = null;
                break;
            case "reload":
                g.setTabItemActived(g.actionTabid);
                g.reload(g.actionTabid);
                break;
        }
    },
    _tabMenuItemClick: function (item) {
        var g = this;
        if (!item.id)
            return;
        g.setTabItemActived(item.id);
    },
    _addTabItemContextMenuEven: function (tabitem) {
        var g = this;
        tabitem.bind("contextmenu", function (e) {
            if (!g.tab.menu)
                return;
            g.actionTabid = tabitem.attr("tabid");
            g.tab.menu.show({
                top: e.pageY,
                left: e.pageX
            });
            if ($(".ux-tab-links-item-close", this).length == 0) {
                g.tab.menu.setDisabled('close');
            } else {
                g.tab.menu.setEnabled('close');
            }
            return false;
        });
    }
});﻿EIAP.ToolBar = function () {
    return new EIAP.toolbar.ToolBar(arguments[0]);
};

EIAP.toolbar.ToolBar = EIAP.extend(EIAP.UIComponent, {
    defaultType: 'Button',
    boxCss: 'ux-toolbar',
    initComponent: function () {
        EIAP.toolbar.ToolBar.superclass.initComponent.call(this);
    },

    __getType: function () {
        return 'ToolBar';
    },
    __idPrev: function () {
        return 'ToolBar';
    },
    _extMethods: function () {
        return EIAP.toolbar.ToolBar;
    },
    _render: function () {
        var g = this;
        g.dom = g.renderTo ? $(this.element) : $("<div></div>");
        g.dom.addClass(g.boxCss);
        g.set(g);
    },
    addItems: function () {
        var g = this, items = this.options.items;
        if (items && g.dom) {
            var flag = false, tb = g.dom;
            g.dom.rightbox = $('<div class="ux-bar-right"></div>');
            for (var i = 0; i < items.length; i++) {
                var item = items[i];
                var xtype = item.xtype ? item.xtype : g.defaultType;
                if (!xtype) {
                    throw new Error(EIAP.error.noXtype);
                }
                if (item == "->") {
                    flag = true;
                    continue;
                }
                if (flag) {
                    g.dom.append(g.dom.rightbox);
                    tb = g.dom.rightbox;
                }
                if (item == "-") {
                    tb.append('<div class="ux-bar-separator"></div>');
                    continue;
                }
                if (xtype) {
                    var cmp = eval("EIAP." + xtype);
                    if (!cmp) {
                        throw new Error(String.format(EIAP.error.noCmp, xtype));
                    }
                    if (xtype == "Button" && typeof item == "object" && item.isFlat == undefined) {
                        item.isFlat = true;
                    }
                    cmp = cmp.call(cmp, item);
                    var itemdom = cmp.dom;
                    itemdom.addClass("ux-toolbar-item");
                    tb.append(itemdom);
                    this.items.push(cmp.id);
                    //if (xtype == "Button") {
                    //    var showtitle = (this.tipText != "" && this.tipText != null && this.tipText != undefined) ? cmp.tipText : cmp.title;
                    //    if (showtitle != "" && showtitle != null) {
                    //        EIAP.ToolTip({ target: itemdom, tipText: showtitle });
                    //    }
                    //}
                }
            }
        }
    }

});
﻿EIAP.Tree = function () {
    return new EIAP.tree.Tree(arguments[0]);
};

EIAP.tree.Tree = EIAP.extend(EIAP.UIComponent, {
    url: null,
    params: null,
    data: null,
    checkbox: false,
    onlyLeafCheck: false,
    autoCheckboxEven: true,
    parentIcon: 'folder',
    childIcon: 'leaf',
    textFieldName: 'text',
    attribute: ['id', 'url'],
    treeLine: true, // 是否显示line
    nodeWidth: 90,
    statusName: '__status',
    isLeaf: null, // 是否子节点的判断函数
    single: false, // 是否单选
    cascadeCheck: true,
    onBeforeExpand: function () { },
    onContextmenu: function () { },
    onExpand: function () { },
    onBeforeCollapse: function () { },
    onCollapse: function () { },
    onBeforeSelect: function () { },
    onSelect: function () { },
    onBeforeCancelSelect: function () { },
    onCancelselect: function () { },
    onCheck: function () { },
    onSuccess: function () { },
    onError: function () { },
    onClick: function () { },
    idFieldName: 'id',
    parentIDFieldName: null,
    topParentIDValue: 0,
    slide: true, // 是否以动画的形式显示
    iconFieldName: 'iconCls',
    nodeDraggable: false, // 是否允许拖拽
    nodeDraggingRender: null,
    btnToggleOnly: true, // 是否点击展开/收缩 按钮时才有效
    needCancel: true, 		//已选的是否需要取消操作
    onBeforeAppend: function () { },        //加载数据前事件，可以通过return false取消操作
    onAppend: function () { },             //加载数据时事件，对数据进行预处理以后
    onAfterAppend: function () { },         //加载数据完事件
    ajaxType: 'post',
    render: null,               //自定义函数
    selectable: null,           //可选择判断函数
    /*
    是否展开 
    1,可以是true/false 
    2,也可以是数字(层次)N 代表第1层到第N层都是展开的，其他收缩
    3,或者是判断函数 函数参数e(data,level) 返回true/false

    优先级没有节点数据的isexpand属性高,并没有delay属性高
    */
    isExpand: null,
    /*
    是否延迟加载 
    1,可以是true/false 
    2,也可以是数字(层次)N 代表第N层延迟加载 
    3,或者是字符串(Url) 加载数据的远程地址
    4,如果是数组,代表这些层都延迟加载,如[1,2]代表第1、2层延迟加载
    5,再是函数(运行时动态获取延迟加载参数) 函数参数e(data,level),返回true/false或者{url:...,parms:...}

    优先级没有节点数据的delay属性高
    */
    delay: null,
    initComponent: function () {
        EIAP.tree.Tree.superclass.initComponent.call(this);
    },
    _init: function () {
        EIAP.tree.Tree.superclass._init.call(this);
        var g = this;
        if (g.single)
            g.autoCheckboxEven = false;
    },
    __getType: function () {
        return 'Tree';
    },
    __idPrev: function () {
        return 'Tree';
    },
    _extMethods: function () {
        return EIAP.tree.Tree;
    },
    _render: function () {
        var g = this;
        g.set(g.options, true);
        g.dom = g.renderTo ? $(g.element) : $("<div></div>");;
        g.dom.addClass('ux-tree');
        g.toggleNodeCallbacks = [];
        g.sysAttribute = ['isexpand', 'ischecked', 'href', 'style', 'delay'];
        g.loading = $("<div class='ux-tree-loading'></div>");
        g.dom.after(g.loading);
        g.maxOutlineLevel = 1;
        g.treedataindex = 0;
        g._applyTree();
        g._setTreeEven();
        g.set(g.options, false);
    },
    _setTreeLine: function (value) {
        if (value)
            this.dom.removeClass("ux-tree-noline");
        else
            this.dom.addClass("ux-tree-noline");
    },
    _setParams: function () {
        var g = this;
        if ($.isFunction(g.params)) g.params = g.params();
    },
    _setUrl: function (url) {
        var g = this;
        if (url) {
            g.clear();
            g.loadData(null, url);
        }
    },
    _setData: function (data) {
        if (data) {
            this.clear();
            this._appendData(null, data);
            this.append(null, data);
        }
    },
    setData: function (data) {
        this.set('data', data);
    },
    getData: function () {
        return this.data;
    },
    //是否包含子节点
    hasChildren: function (treenodedata) {
        if (this.isLeaf) return !this.isLeaf(treenodedata);
        return treenodedata.children ? true : false;
    },
    //获取父节点 数据
    getParent: function (treenode, level) {
        var g = this;
        treenode = g.getNodeDom(treenode);
        var parentTreeNode = g.getParentTreeItem(treenode, level);
        if (!parentTreeNode) return null;
        var parentIndex = $(parentTreeNode).attr("treedataindex");
        return g._getDataNodeByTreeDataIndex(parentIndex);
    },
    //获取父节点
    getParentTreeItem: function (treenode, level) {
        var g = this;
        treenode = g.getNodeDom(treenode);
        var treeitem = $(treenode);
        if (treeitem.parent().hasClass("ux-tree"))
            return null;
        if (level == undefined) {
            if (treeitem.parent().parent("li").length == 0)
                return null;
            return treeitem.parent().parent("li")[0];
        }
        var currentLevel = parseInt(treeitem.attr("outlinelevel"));
        var currenttreeitem = treeitem;
        for (var i = currentLevel - 1; i >= level; i--) {
            currenttreeitem = currenttreeitem.parent().parent("li");
        }
        return currenttreeitem[0];
    },
    getChecked: function () {
        var g = this;
        if (!this.checkbox) return null;
        var nodes = [];
        $(".ux-checkbox-checked", g.dom).parent().parent("li").each(function () {
            var treedataindex = parseInt($(this).attr("treedataindex"));
            nodes.push({ target: this, data: g._getDataNodeByTreeDataIndex(g.data, treedataindex) });
        });
        return nodes;
    },
    getSelected: function () {
        var g = this;
        var node = {};
        node.target = $(".ux-selected", g.dom).parent("li")[0];
        if (node.target) {
            var treedataindex = parseInt($(node.target).attr("treedataindex"));
            node.data = g._getDataNodeByTreeDataIndex(g.data, treedataindex);
            return node;
        }
        return null;
    },
    isSelected: function (node) {
        if (node) {
            var sel = $(node.target).hasClass("ux-selected");
            if (!sel) {
                sel = $(".ux-body:first", node.target).hasClass("ux-selected");
            }
            return sel;
        }
        return false;
    },
    //升级为父节点级别
    upgrade: function (treeNode) {
        var g = this;
        $(".ux-note", treeNode).each(function () {
            $(this).removeClass("ux-note").addClass("ux-expandable-open");
        });
        $(".ux-note-last", treeNode).each(function () {
            $(this).removeClass("ux-note-last").addClass("ux-expandable-open");
        });
        $("." + g._getChildNodeClassName(), treeNode).each(function () {
            $(this).removeClass(g._getChildNodeClassName()).addClass(g._getParentNodeClassName(true));
        });
    },
    //降级为叶节点级别
    demotion: function (treeNode) {
        var g = this;
        if (!treeNode && treeNode[0].tagName.toLowerCase() != 'li') return;
        var islast = $(treeNode).hasClass("ux-last");
        $(".ux-expandable-open", treeNode).each(function () {
            $(this).removeClass("ux-expandable-open")
                        .addClass(islast ? "ux-note-last" : "ux-note");
        });
        $(".ux-expandable-close", treeNode).each(function () {
            $(this).removeClass("ux-expandable-close").addClass(islast ? "ux-note-last" : "ux-note");
        });
        $("." + g._getParentNodeClassName(true), treeNode).each(function () {
            $(this).removeClass(g._getParentNodeClassName(true)).addClass(g._getChildNodeClassName());
        });
    },
    collapseAll: function () {
        var g = this;
        $(".ux-expandable-open", g.dom).click();
    },
    expandAll: function () {
        var g = this;
        $(".ux-expandable-close", g.dom).click();
    },
    loadData: function (node, url, param, e) {
        var g = this;
        e = $.extend({
            showLoading: function () {
                g.loading.show();
            },
            hideLoading: function () {
                g.loading.hide();
            }
        }, e || {});
        param = param || {};
        //请求服务器
        $.ajax({
            type: g.ajaxType,
            url: url,
            data: param,
            dataType: 'json',
            beforeSend: function () {
                e.showLoading();
            },
            success: function (data) {
                if (!data) return;
                e.hideLoading();
                if (!node) {
                    g.data = data;
                } else {
                    g._appendData(node, data);
                }
                g.append(node, data);
                g.trigger('success', [data]);
            },
            error: function (xmlHttpRequest, textStatus, errorThrown) {
                try {
                    e.hideLoading();
                    g.trigger('error', [xmlHttpRequest, textStatus, errorThrown]);
                }
                catch (ex) { }
            }
        });
    },
    // 清空
    clear: function () {
        var g = this;
        g.toggleNodeCallbacks = [];
        g.data = [];
        g.nodes = null;
        g.dom.html("");
    },
    // @parm [treeNode] dom节点(li)、节点数据 或者节点 dataindex
    getNodeDom: function (nodeParm) {
        var g = this;
        if (nodeParm == null)
            return nodeParm;
        if (typeof (nodeParm) == "string" || typeof (nodeParm) == "number") {
            return $("li[treedataindex=" + nodeParm + "]", g.dom).get(0);
        } else if (typeof (nodeParm) == "object") {
            if (nodeParm instanceof Array && 'treedataindex' in nodeParm[0]) // nodedata
            {
                return g.getNodeDom(nodeParm[0]['treedataindex']);
            }
        }
        return nodeParm;
    },
    hide: function (treeNode) {
        var g = this;
        treeNode = g.getNodeDom(treeNode);
        if (treeNode) $(treeNode).hide();
    },
    show: function (treeNode) {
        var g = this;
        treeNode = g.getNodeDom(treeNode);
        if (treeNode) $(treeNode).show();
    },
    // @parm [treeNode] dom节点(li)、节点数据 或者节点 dataindex
    remove: function (treeNode) {
        var g = this;
        treeNode = g.getNodeDom(treeNode);
        var treedataindex = parseInt($(treeNode).attr("treedataindex"));
        var treenodedata = g._getDataNodeByTreeDataIndex(g.data, treedataindex);
        if (treenodedata)
            g._setTreeDataStatus([treenodedata], 'delete');
        var parentNode = g.getParentTreeItem(treeNode);
        // 复选框处理
        if (g.checkbox && g.cascadeCheck) {
            g._setParentCheckboxStatus($(treeNode));
        }
        $(treeNode).remove();
        g._updateStyle(parentNode ? $("ul:first", parentNode) : g.dom);
    },
    _updateStyle: function (ul) {
        var g = this;
        var itmes = $(" > li", ul);
        var treeitemlength = itmes.length;
        if (!treeitemlength)
            return;
        // 遍历设置子节点的样式
        itmes.each(function (i, item) {
            if (i == 0 && !$(this).hasClass("ux-first"))
                $(this).addClass("ux-first");
            if (i == treeitemlength - 1 && !$(this).hasClass("ux-last"))
                $(this).addClass("ux-last");
            if (i == 0 && i == treeitemlength - 1)
                $(this).addClass("ux-onlychild");
            $("> div .ux-note,> div .ux-note-last", this)
							.removeClass("ux-note ux-note-last")
							.addClass(i == treeitemlength - 1
									? "ux-note-last"
									: "ux-note");
            g._setTreeItem(this, {
                isLast: i == treeitemlength - 1
            });
        });
    },
    // @parm [domnode] dom节点(li)、节点数据 或者节点 dataindex
    update: function (domnode, newnodedata) {
        var g = this;
        domnode = g.getNodeDom(domnode);
        var treedataindex = parseInt($(domnode).attr("treedataindex"));
        nodedata = g._getDataNodeByTreeDataIndex(g.data, treedataindex);
        for (var attr in newnodedata) {
            nodedata[attr] = newnodedata[attr];
            if (attr == g.textFieldName) {
                $("> .ux-body > span", domnode).text(newnodedata[attr]);
            }
        }
    },
    // 增加节点集合
    // @parm [newdata] 数据集合 Array
    // @parm [parentNode] dom节点(li)、节点数据 或者节点 dataindex
    // @parm [nearNode] 附加到节点的上方/下方(非必填)
    // @parm [isAfter] 附加到节点的下方(非必填)
    append: function (parentNode, newdata, nearNode, isAfter) {
        var g = this;
        parentNode = g.getNodeDom(parentNode);
        if (g.trigger('beforeAppend', [parentNode, newdata]) == false)
            return false;
        if (!newdata || !newdata.length)
            return false;
        if (g.idFieldName && g.parentIDFieldName)
            newdata = g.arrayToTree(newdata, g.idFieldName, g.parentIDFieldName);
        g._addTreeDataIndexToData(newdata);
        g._setTreeDataStatus(newdata, 'add');
        if (nearNode != null) {
            nearNode = g.getNodeDom(nearNode);
        }
        g.trigger('append', [parentNode, newdata]);
        //g._appendData(parentNode, newdata);
        var gridhtmlarr = g._getTreeHTMLByData(newdata, 1, [], true);
        if (parentNode == null)// 增加到根节点
        {
            gridhtmlarr[gridhtmlarr.length - 1] = gridhtmlarr[0] = "";
            if (nearNode != null) {
                $(nearNode)[isAfter ? 'after' : 'before'](gridhtmlarr.join(''));
                g._updateStyle(parentNode ? $("ul:first", parentNode) : g.dom);
            } else {
                // remove last node class
                if ($("> li:last", g.dom).length > 0)
                    g._setTreeItem($("> li:last", g.dom)[0], {
                        isLast: false
                    });
                g.dom.append(gridhtmlarr.join(''));
            }
            $(".ux-body", g.dom).hover(function () {
                $(this).addClass("ux-over");
            }, function () {
                $(this).removeClass("ux-over");
            });
            g._upadteTreeWidth();
            g.trigger('afterAppend', [parentNode, newdata]);
            return;
        }
        var treeitem = $(parentNode);
        var outlineLevel = parseInt(treeitem.attr("outlinelevel"));
        var hasChildren = $("> ul", treeitem).length > 0;
        if (!hasChildren) {
            treeitem.append("<ul class='ux-children'></ul>");
            // 设置为父节点
            g.upgrade(parentNode);
        }
        var isLast = [];
        for (var i = 1; i <= outlineLevel - 1; i++) {
            var currentParentTreeItem = $(g.getParentTreeItem(parentNode, i));
            isLast.push(currentParentTreeItem.hasClass("ux-last"));
        }
        isLast.push(treeitem.hasClass("ux-last"));
        gridhtmlarr = g._getTreeHTMLByData(newdata, outlineLevel + 1, isLast, true);
        gridhtmlarr[gridhtmlarr.length - 1] = gridhtmlarr[0] = "";
        if (nearNode != null) {
            $(nearNode)[isAfter ? 'after' : 'before'](gridhtmlarr.join(''));
            g._updateStyle(parentNode ? $("ul:first", parentNode) : g.dom);
        } else {
            // remove last node class
            if ($("> .ux-children > li:last", treeitem).length > 0)
                g._setTreeItem($("> .ux-children > li:last", treeitem)[0], {
                    isLast: false
                });
            $(">.ux-children", parentNode).append(gridhtmlarr.join(''));
        }
        g._upadteTreeWidth();
        $(">.ux-children .ux-body", parentNode).hover(function () {
            $(this).addClass("ux-over");
        }, function () {
            $(this).removeClass("ux-over");
        });
        g.trigger('afterAppend', [parentNode, newdata]);
    },
    resetSelect: function () {
        var g = this;
        $("li", g.dom).each(function () {
            g.cancelSelect(this);
        });
    },
    // @parm [nodeParm] dom节点(li)、节点数据 或者节点 dataindex
    cancelSelect: function (nodeParm) {
        var g = this;
        var domNode = g.getNodeDom(nodeParm);
        var treeitem = $(domNode);
        var treedataindex = parseInt(treeitem.attr("treedataindex"));
        var treenodedata = g._getDataNodeByTreeDataIndex(g.data, treedataindex);
        var treeitembody = $(">div:first", treeitem);
        if (g.checkbox)
            $(".ux-checkbox", treeitembody).removeClass("ux-checkbox-checked")
					.addClass("ux-checkbox-unchecked");
        else
            treeitembody.removeClass("ux-selected");
        g.trigger('cancelSelect', [{
            data: treenodedata,
            target: treeitem[0]
        }]);
    },
    // 选择节点(参数：条件函数、Dom节点或ID值)
    selectNode: function (selectNodeParm) {
        var g = this;
        var clause = null, treeitem, treedataindex, treenodedata;
        if (typeof (selectNodeParm) == "function") {
            clause = selectNodeParm;
        } else if (typeof (selectNodeParm) == "object") {
            treeitem = $(selectNodeParm);
            treedataindex = parseInt(treeitem.attr("treedataindex"));
            treenodedata = g._getDataNodeByTreeDataIndex(g.data, treedataindex);
            var treeitembody = $(">div:first", treeitem);
            if (g.checkbox)
                $(".ux-checkbox", treeitembody)
						.removeClass("ux-checkbox-unchecked")
						.addClass("ux-checkbox-checked");
            else
                treeitembody.addClass("ux-selected");

            g.trigger('select', [{
                data: treenodedata,
                target: treeitem[0]
            }]);
            return;
        } else {
            clause = function (data) {
                if (!data[g.idFieldName])
                    return false;
                return data[g.idFieldName].toString() == selectNodeParm
						.toString();
            };
        }
        $("li", g.dom).each(function () {
            treeitem = $(this);
            treedataindex = parseInt(treeitem.attr("treedataindex"));
            treenodedata = g._getDataNodeByTreeDataIndex(g.data, treedataindex);
            if (clause(treenodedata, treedataindex)) {
                g.selectNode(this);
            } else {
                g.cancelSelect(this);
            }
        });
    },
    getTextByID: function (id) {
        var g = this;
        var data = g.getDataByID(id);
        if (!data)
            return null;
        return data[g.textFieldName];
    },
    getDataByID: function (id) {
        var g = this;
        var data = null;
        $("li", g.dom).each(function () {
            if (data) return;
            var treeitem = $(this);
            var treedataindex = parseInt(treeitem.attr("treedataindex"));
            var treenodedata = g._getDataNodeByTreeDataIndex(g.data, treedataindex);
            if (treenodedata[g.idFieldName].toString() == id.toString()) {
                data = treenodedata;
            }
        });
        return data;
    },
    arrayToTree: function (data, id, pid) // 将ID、ParentID这种数据格式转换为树格式
    {
        if (!data || !data.length)
            return [];
        var targetData = []; // 存储数据的容器(返回)
        var records = {};
        var itemLength = data.length; // 数据集合的个数
        for (var i = 0; i < itemLength; i++) {
            var o = data[i];
            records[o[id]] = o;
        }
        for (var i = 0; i < itemLength; i++) {
            var currentData = data[i];
            var parentData = records[currentData[pid]];
            if (!parentData) {
                targetData.push(currentData);
                continue;
            }
            parentData.children = parentData.children || [];
            parentData.children.push(currentData);
        }
        return targetData;
    },
    // 根据数据索引获取数据
    _getDataNodeByTreeDataIndex: function (data, treedataindex) {
        var g = this;
        for (var i = 0; i < data.length; i++) {
            if (data[i].treedataindex == treedataindex)
                return data[i];
            if (data[i].children) {
                var targetData = g._getDataNodeByTreeDataIndex(
						data[i].children, treedataindex);
                if (targetData)
                    return targetData;
            }
        }
        return null;
    },
    // 设置数据状态
    _setTreeDataStatus: function (data, status) {
        var g = this;
        $(data).each(function () {
            this[g.statusName] = status;
            if (this.children) {
                g._setTreeDataStatus(this.children, status);
            }
        });
    },
    // 设置data 索引
    _addTreeDataIndexToData: function (data) {
        var g = this;
        $(data).each(function () {
            if (this.treedataindex != undefined) return;
            this.treedataindex = g.treedataindex++;
            if (this.children) {
                g._addTreeDataIndexToData(this.children);
            }
        });
    },
    _addToNodes: function (data) {
        var g = this;
        g.nodes = g.nodes || [];
        if ($.inArray(data, g.nodes) == -1)
            g.nodes.push(data);
        if (data.children) {
            $(data.children).each(function (i, item) {
                g._addToNodes(item);
            });
        }
    },
    // 添加项到g.data
    _appendData: function (treeNode, data) {
        var g = this;
        var treedataindex = parseInt($(treeNode).attr("treedataindex"));
        var treenodedata = g._getDataNodeByTreeDataIndex(g.data, treedataindex);
        if (g.treedataindex == undefined)
            g.treedataindex = 0;
        if (treenodedata && treenodedata.children == undefined)
            treenodedata.children = [];
        $(data).each(function (i, item) {
            if (treenodedata)
                treenodedata.children[treenodedata.children.length] = item;
            else
                g.data[g.data.length] = item;
            g._addToNodes(item);
        });
    },
    _setTreeItem: function (treeNode, options) {
        var g = this;
        if (!options) return;
        treeNode = g.getNodeDom(treeNode);
        var treeItem = $(treeNode);
        var outlineLevel = parseInt(treeItem.attr("outlinelevel"));
        if (options.isLast != undefined) {
            if (options.isLast == true) {
                treeItem.removeClass("ux-last").addClass("ux-last");
                $("> div .ux-note", treeItem).removeClass("ux-note")
						.addClass("ux-note-last");
                $(".ux-children li", treeItem).find(".ux-box:eq("
						+ (outlineLevel - 1) + ")").removeClass("ux-line");
            } else if (options.isLast == false) {
                treeItem.removeClass("ux-last");
                $("> div .ux-note-last", treeItem).removeClass("ux-note-last")
						.addClass("ux-note");

                $(".ux-children li", treeItem).find(".ux-box:eq("
						+ (outlineLevel - 1) + ")").removeClass("ux-line")
						.addClass("ux-line");
            }
        }
    },
    _upadteTreeWidth: function () {
        var g = this;
        var treeWidth = g.maxOutlineLevel * 22;
        if (g.checkbox)
            treeWidth += 22;
        if (g.parentIcon || g.childIcon)
            treeWidth += 22;
        treeWidth += g.nodeWidth;
        g.dom.treeWidth = treeWidth;
    },
    _getChildNodeClassName: function () {
        var g = this;
        return 'ux-tree-icon-' + g.childIcon;
    },
    _getParentNodeClassName: function (isOpen) {
        var g = this;
        var nodeclassname = 'ux-tree-icon-' + g.parentIcon;
        if (isOpen)
            nodeclassname += '-open';
        return nodeclassname;
    },
    //判断节点是否展开状态,返回true/false
    _isExpand: function (o, level) {
        var g = this;
        var isExpand = o.isExpand != null ? o.isExpand : (o.isexpand != null ? o.isexpand : g.isExpand);
        if (isExpand == null) return false;
        if (typeof (isExpand) == "function") isExpand = g.isExpand({ data: o, level: level });
        if (typeof (isExpand) == "boolean") return isExpand;
        if (typeof (isExpand) == "string") return isExpand == "true";
        if (typeof (isExpand) == "number") return isExpand > level;
        return true;
    },
    //获取节点的延迟加载状态,返回true/false (本地模式) 或者是object({url :'...',params:null})(远程模式)
    _getDelay: function (o, level) {
        var g = this;
        var delay = o.delay != null ? o.delay : g.delay;
        if (delay == null) return false;
        if (typeof (delay) == "function") delay = delay({ data: o, level: level });
        if (typeof (delay) == "boolean") return delay;
        if (typeof (delay) == "string") return { url: delay };
        if (typeof (delay) == "number") delay = [delay];
        if ($.isArray(delay)) return $.inArray(level, delay) != -1;
        if (delay && typeof (delay) == "object" && delay.url) return delay;
        return false;
    },
    // 根据data生成最终完整的tree html
    _getTreeHTMLByData: function (data, outlineLevel, isLast, isExpand) {
        var g = this;
        if (g.maxOutlineLevel < outlineLevel)
            g.maxOutlineLevel = outlineLevel;
        isLast = isLast || [];
        outlineLevel = outlineLevel || 1;
        var treehtmlarr = [];
        if (!isExpand)
            treehtmlarr.push('<ul class="ux-children" style="display:none">');
        else
            treehtmlarr.push("<ul class='ux-children'>");
        for (var i = 0; i < data.length; i++) {
            var isFirst = i == 0;
            var isLastCurrent = i == data.length - 1;
            var o = data[i];
            var delay = g._getDelay(o, outlineLevel);
            var isExpandCurrent = delay ? false : g._isExpand(o, outlineLevel);
            treehtmlarr.push('<li ');
            if (o.treedataindex != undefined)
                treehtmlarr.push('treedataindex="' + o.treedataindex + '" ');
            if (isExpandCurrent)
                treehtmlarr.push('isexpand=' + o.isexpand + ' ');
            treehtmlarr.push('outlinelevel=' + outlineLevel + ' ');
            // 增加属性支持
            for (var j = 0; j < g.sysAttribute.length; j++) {
                if ($(this).attr(g.sysAttribute[j]))
                    data[i][g.sysAttribute[j]] = $(this)
							.attr(g.sysAttribute[j]);
            }
            for (var j = 0; j < g.attribute.length; j++) {
                if (o[g.attribute[j]])
                    treehtmlarr.push(g.attribute[j] + '="' + o[g.attribute[j]]
							+ '" ');
            }
            // css class
            treehtmlarr.push('class="');
            isFirst && treehtmlarr.push('ux-first ');
            isLastCurrent && treehtmlarr.push('ux-last ');
            isFirst && isLastCurrent && treehtmlarr.push('ux-onlychild ');
            treehtmlarr.push('"');
            treehtmlarr.push('>');
            var t = o.Path || o[g.textFieldName];
            treehtmlarr.push('<div title="' + t + '" class="ux-body');
            if (g.selectable && g.selectable(o) == false) {
                treehtmlarr.push(' ux-unselectable');
            }
            treehtmlarr.push('">');
            for (var k = 0; k <= outlineLevel - 2; k++) {
                if (isLast[k])
                    treehtmlarr.push('<div class="ux-box"></div>');
                else
                    treehtmlarr.push('<div class="ux-box ux-line"></div>');
            }
            if (g.hasChildren(o)) {
                if (isExpandCurrent)
                    treehtmlarr
							.push('<div class="ux-box ux-expandable-open"></div>');
                else
                    treehtmlarr
							.push('<div class="ux-box ux-expandable-close"></div>');
                if (g.checkbox && !g.onlyLeafCheck) {
                    if (o.ischecked)
                        treehtmlarr
                            .push('<div class="ux-box ux-checkbox ux-checkbox-checked"></div>');
                    else
                        treehtmlarr
                            .push('<div class="ux-box ux-checkbox ux-checkbox-unchecked"></div>');
                }
                if (g.parentIcon) {
                    // node icon
                    treehtmlarr.push('<div class="ux-box ux-tree-icon ');
                    treehtmlarr.push(g._getParentNodeClassName(isExpandCurrent ? true : false) + " ");
                    if (g.iconFieldName && o[g.iconFieldName])
                        treehtmlarr.push('ux-tree-icon-none');
                    treehtmlarr.push('">');
                    if (g.iconFieldName && o[g.iconFieldName])
                        treehtmlarr.push('<img src="' + EIAP.BLANK_IMAGE_URL
								+ '" class="' + o[g.iconFieldName] + '" />');
                    treehtmlarr.push('</div>');
                }
            } else {
                if (isLastCurrent)
                    treehtmlarr.push('<div class="ux-box ux-note-last"></div>');
                else
                    treehtmlarr.push('<div class="ux-box ux-note"></div>');
                if (g.checkbox) {
                    if (o.ischecked)
                        treehtmlarr
								.push('<div class="ux-box ux-checkbox ux-checkbox-checked"></div>');
                    else
                        treehtmlarr
								.push('<div class="ux-box ux-checkbox ux-checkbox-unchecked"></div>');
                }
                if (g.childIcon) {
                    // node icon
                    treehtmlarr.push('<div class="ux-box ux-tree-icon ');
                    treehtmlarr.push(g._getChildNodeClassName() + " ");
                    if (g.iconFieldName && o[g.iconFieldName])
                        treehtmlarr.push('ux-tree-icon-none');
                    treehtmlarr.push('">');
                    if (g.iconFieldName && o[g.iconFieldName])
                        treehtmlarr.push('<img src="' + EIAP.BLANK_IMAGE_URL
								+ '" class="' + o[g.iconFieldName] + '" />');
                    treehtmlarr.push('</div>');
                }
            }
            if (g.render) {
                treehtmlarr.push('<span>' + g.render(o, o[g.textFieldName]) + '</span>');
            } else {
                treehtmlarr.push('<span>' + o[g.textFieldName] + '</span>');
            }
            treehtmlarr.push('</div>');
            if (g.hasChildren(o)) {
                var isLastNew = [];
                for (var k = 0; k < isLast.length; k++) {
                    isLastNew.push(isLast[k]);
                }
                isLastNew.push(isLastCurrent);
                if (delay) {
                    if (delay == true) {
                        g.toggleNodeCallbacks.push({
                            data: o,
                            callback: function (dom, o) {
                                var content = g._getTreeHTMLByData(o.children, outlineLevel + 1, isLastNew, isExpandCurrent).join('');
                                $(dom).append(content);
                                $(">.ux-children .ux-body", dom).hover(function () {
                                    $(this).addClass("ux-over");
                                }, function () {
                                    $(this).removeClass("ux-over");
                                });
                                g._removeToggleNodeCallback(o);
                            }
                        });
                    } else if (delay.url) {
                        (function (o, url, params) {
                            g.toggleNodeCallbacks.push({
                                data: o,
                                callback: function (dom, o) {
                                    g.loadData(dom, url, params, {
                                        showLoading: function () {
                                            $("div.ux-expandable-close:first", dom).addClass("ux-box-loading");
                                        },
                                        hideLoading: function () {
                                            $("div.ux-box-loading:first", dom).removeClass("ux-box-loading");
                                        }
                                    });
                                    g._removeToggleNodeCallback(o);
                                }
                            });
                        })(o, delay.url, delay.params);
                    }
                } else {
                    treehtmlarr.push(g._getTreeHTMLByData(o.children,
                        outlineLevel + 1, isLastNew, isExpandCurrent).join(''));
                }
            }
            treehtmlarr.push('</li>');
        }
        treehtmlarr.push("</ul>");
        return treehtmlarr;

    },
    _removeToggleNodeCallback: function (nodeData) {
        var g = this;
        for (var i = 0; i <= g.toggleNodeCallbacks.length; i++) {
            if (g.toggleNodeCallbacks[i] && g.toggleNodeCallbacks[i].data == nodeData) {
                g.toggleNodeCallbacks.splice(i, 1);
                break;
            }
        }
    },
    //根据简洁的html获取data
    _getDataByTreeHTML: function (treeDom) {
        var g = this;
        var data = [];
        $("> li", treeDom).each(function (i, item) {
            var dataindex = data.length;
            data[dataindex] =
                        {
                            treedataindex: g.treedataindex++
                        };
            data[dataindex][g.textFieldName] = $("> span,> a", this).html();
            for (var j = 0; j < g.sysAttribute.length; j++) {
                if ($(this).attr(g.sysAttribute[j]))
                    data[dataindex][g.sysAttribute[j]] = $(this).attr(g.sysAttribute[j]);
            }
            for (var j = 0; j < g.attribute.length; j++) {
                if ($(this).attr(g.attribute[j]))
                    data[dataindex][g.attribute[j]] = $(this).attr(g.attribute[j]);
            }
            if ($("> ul", this).length > 0) {
                data[dataindex].children = g._getDataByTreeHTML($("> ul", this));
            }
        });
        return data;
    },
    _applyTree: function () {
        var g = this;
        g.data = g._getDataByTreeHTML(g.dom);
        var gridhtmlarr = g._getTreeHTMLByData(g.data, 1, [], true);
        gridhtmlarr[gridhtmlarr.length - 1] = gridhtmlarr[0] = "";
        g.dom.html(gridhtmlarr.join(''));
        g._upadteTreeWidth();
        $(".ux-body", g.dom).hover(function () {
            $(this).addClass("ux-over");
        }, function () {
            $(this).removeClass("ux-over");
        });
    },
    _getSrcElementByEvent: function (e) {
        var g = this;
        var obj = (e.target || e.srcElement);
        var tag = obj.tagName.toLowerCase();
        var jobjs = $(obj).parents().add(obj);
        var fn = function (parm) {
            for (var i = jobjs.length - 1; i >= 0; i--) {
                if ($(jobjs[i]).hasClass(parm))
                    return jobjs[i];
            }
            return null;
        };
        if (jobjs.index(this.element) == -1)
            return {
                out: true
            };
        var r = {
            tree: fn("ux-tree"),
            node: fn("ux-body"),
            checkbox: fn("ux-checkbox"),
            icon: fn("ux-tree-icon"),
            text: tag == "span"
        };
        if (r.node) {
            var treedataindex = parseInt($(r.node).parent()
					.attr("treedataindex"));
            r.data = g._getDataNodeByTreeDataIndex(g.data, treedataindex);
        }
        return r;
    },
    _setTreeEven: function () {
        var g = this;
        if (g.hasBind('contextmenu') || g.contextMenu) {
            g.dom.bind("contextmenu", function (e) {
                var obj = (e.target || e.srcElement);
                var treeitem = null;
                if (obj.tagName.toLowerCase() == "a"
								|| obj.tagName.toLowerCase() == "span"
								|| $(obj).hasClass("ux-box"))
                    treeitem = $(obj).parent().parent();
                else if ($(obj).hasClass("ux-body"))
                    treeitem = $(obj).parent();
                else if (obj.tagName.toLowerCase() == "li")
                    treeitem = $(obj);
                if (!treeitem) return;
                var treedataindex = parseInt(treeitem.attr("treedataindex"));
                var treenodedata = g._getDataNodeByTreeDataIndex(g.data, treedataindex);
                var node = {
                    data: treenodedata,
                    target: treeitem[0]
                };
                if (!g.isSelected(node)) {
                    $(node.target).click();
                }
                if (g.contextMenu && EIAP.menu.Menu) {
                    g.contextMenu.show({
                        top: e.pageY,
                        left: e.pageX
                    });
                    g.trigger('contextmenu', [node, e]);
                    return false;
                }
            });
        }
        g.dom.click(function (e) {
            var obj = (e.target || e.srcElement);
            var treeitem = null;
            if (obj.tagName.toLowerCase() == "a"
					|| obj.tagName.toLowerCase() == "span"
					|| $(obj).hasClass("ux-box"))
                treeitem = $(obj).parent().parent();
            else if ($(obj).hasClass("ux-body"))
                treeitem = $(obj).parent();
            else
                treeitem = $(obj);
            if (!treeitem) return;
            var treedataindex = parseInt(treeitem.attr("treedataindex"));
            var treenodedata = g._getDataNodeByTreeDataIndex(g.data, treedataindex);
            var treeitembtn = $("div.ux-body:first", treeitem)
					.find("div.ux-expandable-open:first,div.ux-expandable-close:first");
            var clickOnTreeItemBtn = $(obj).hasClass("ux-expandable-open")
					|| $(obj).hasClass("ux-expandable-close");
            if (!$(obj).hasClass("ux-checkbox") && !clickOnTreeItemBtn) {
                if (!treeitem.hasClass("ux-unselectable")) {
                    if ($(">div:first", treeitem).hasClass("ux-selected")) {
                        if (g.trigger('beforeCancelSelect', [{ data: treenodedata, target: treeitem[0] }]) == false)
                            return false;
                        $(">div:first", treeitem).removeClass("ux-selected");
                        g.trigger('cancelSelect', [{ data: treenodedata, target: treeitem[0] }]);
                    } else {
                        if (g.trigger('beforeSelect', [{ data: treenodedata, target: treeitem[0] }]) == false)
                            return false;
                        $(".ux-body", g.dom).removeClass("ux-selected");
                        $(">div:first", treeitem).addClass("ux-selected");
                        g.trigger('select', [{
                            data: treenodedata,
                            target: treeitem[0]
                        }]);
                    }
                }
            }
            // chekcbox even
            if ($(obj).hasClass("ux-checkbox")) {
                if (g.autoCheckboxEven) {
                    // 状态：未选中
                    if ($(obj).hasClass("ux-checkbox-unchecked")) {
                        $(obj).removeClass("ux-checkbox-unchecked")
								.addClass("ux-checkbox-checked");
                        $(".ux-children .ux-checkbox", treeitem)
								.removeClass("ux-checkbox-incomplete ux-checkbox-unchecked")
								.addClass("ux-checkbox-checked");
                        g.trigger('check', [{
                            data: treenodedata,
                            target: treeitem[0]
                        }, true]);
                    }
                        // 状态：选中
                    else if ($(obj).hasClass("ux-checkbox-checked")) {
                        $(obj).removeClass("ux-checkbox-checked")
								.addClass("ux-checkbox-unchecked");
                        $(".ux-children .ux-checkbox", treeitem)
								.removeClass("ux-checkbox-incomplete ux-checkbox-checked")
								.addClass("ux-checkbox-unchecked");
                        g.trigger('check', [{
                            data: treenodedata,
                            target: treeitem[0]
                        }, false]);
                    }
                        // 状态：未完全选中
                    else if ($(obj).hasClass("ux-checkbox-incomplete")) {
                        $(obj).removeClass("ux-checkbox-incomplete")
								.addClass("ux-checkbox-checked");
                        $(".ux-children .ux-checkbox", treeitem)
								.removeClass("ux-checkbox-incomplete ux-checkbox-unchecked")
								.addClass("ux-checkbox-checked");
                        g.trigger('check', [{
                            data: treenodedata,
                            target: treeitem[0]
                        }, true]);
                    }
                    g.cascadeCheck && g._setParentCheckboxStatus(treeitem);
                } else {
                    // 状态：未选中
                    if ($(obj).hasClass("ux-checkbox-unchecked")) {
                        $(obj).removeClass("ux-checkbox-unchecked")
								.addClass("ux-checkbox-checked");
                        // 是否单选
                        if (g.single) {
                            $(".ux-checkbox", g.dom).not(obj)
									.removeClass("ux-checkbox-checked")
									.addClass("ux-checkbox-unchecked");
                        }
                        g.trigger('check', [{
                            data: treenodedata,
                            target: treeitem[0]
                        }, true]);
                    }
                        // 状态：选中
                    else if ($(obj).hasClass("ux-checkbox-checked")) {
                        $(obj).removeClass("ux-checkbox-checked")
								.addClass("ux-checkbox-unchecked");
                        g.trigger('check', [{
                            data: treenodedata,
                            target: treeitem[0]
                        }, false]);
                    }
                }
                return false;
            }
                // 状态：已经张开
            else if (treeitembtn.hasClass("ux-expandable-open")
					&& (!g.btnToggleOnly || clickOnTreeItemBtn)) {
                if (g.trigger('beforeCollapse', [{
                    data: treenodedata,
                    target: treeitem[0]
                }]) == false)
                    return false;
                treeitembtn.removeClass("ux-expandable-open")
						.addClass("ux-expandable-close");
                if (g.slide)
                    $("> .ux-children", treeitem).slideToggle('fast');
                else
                    $("> .ux-children", treeitem).toggle();
                $("> div ." + g._getParentNodeClassName(true), treeitem)
						.removeClass(g._getParentNodeClassName(true))
						.addClass(g._getParentNodeClassName());
                g.trigger('collapse', [{
                    data: treenodedata,
                    target: treeitem[0]
                }]);
                return false;
            }
                // 状态：没有张开
            else if (treeitembtn.hasClass("ux-expandable-close")
					&& (!g.btnToggleOnly || clickOnTreeItemBtn)) {
                if (g.trigger('beforeExpand', [{
                    data: treenodedata,
                    target: treeitem[0]
                }]) == false)
                    return false;
                $(g.toggleNodeCallbacks).each(function () {
                    if (this.data == treenodedata) {
                        this.callback(treeitem[0], treenodedata);
                    }
                });
                treeitembtn.removeClass("ux-expandable-close")
						.addClass("ux-expandable-open");
                var callback = function () {
                    g.trigger('expand', [{
                        data: treenodedata,
                        target: treeitem[0]
                    }]);
                };
                if (g.slide) {
                    $("> .ux-children", treeitem).slideToggle('fast', callback);
                } else {
                    $("> .ux-children", treeitem).show();
                    callback();
                }
                $("> div ." + g._getParentNodeClassName(), treeitem)
						.removeClass(g._getParentNodeClassName()).addClass(g
								._getParentNodeClassName(true));
                return false;
            }
            g.trigger('click', [{
                data: treenodedata,
                target: treeitem[0]
            }]);
            return false;
        });

        // 节点拖拽支持
        if ($.fn.eiapDrag && g.nodeDraggable) {
            g.nodeDroptip = $("<div class='ux-drag-nodedroptip' style='display:none'></div>")
					.appendTo('body');
            g.dom.eiapDrag({
                revert: true,
                animate: false,
                proxyX: 20,
                proxyY: 20,
                proxy: function (draggable, e) {
                    var src = g._getSrcElementByEvent(e);
                    if (src.node) {
                        var content = "dragging";
                        if (g.nodeDraggingRender) {
                            content = g.nodeDraggingRender(
									draggable.draggingNodes, draggable, g);
                        } else {
                            content = "";
                            var appended = false;
                            for (var i in draggable.draggingNodes) {
                                var node = draggable.draggingNodes[i];
                                if (appended)
                                    content += ",";
                                content += node.text;
                                appended = true;
                            }
                        }
                        var proxy = $("<div class='ux-drag-proxy' style='display:none'><div class='ux-drop-icon ux-drop-no'></div>"
								+ content + "</div>").appendTo('body');
                        return proxy;
                    }
                },
                onRevert: function () {
                    return false;
                },
                onRendered: function () {
                    this.set('cursor', 'default');
                    g.children[this.id] = this;
                },
                onStartDrag: function (current, e) {
                    if (e.button == 2)
                        return false;
                    this.set('cursor', 'default');
                    var src = g._getSrcElementByEvent(e);
                    if (src.checkbox)
                        return false;
                    if (g.checkbox) {
                        var checked = g.getChecked();
                        this.draggingNodes = [];
                        for (var i in checked) {
                            this.draggingNodes.push(checked[i].data);
                        }
                        if (!this.draggingNodes || !this.draggingNodes.length)
                            return false;
                    } else {
                        this.draggingNodes = [src.data];
                    }
                    this.draggingNode = src.data;
                    this.set('cursor', 'move');
                    g.nodedragging = true;
                    this.validRange = {
                        top: g.dom.offset().top,
                        bottom: g.dom.offset().top + g.dom.height(),
                        left: g.dom.offset().left,
                        right: g.dom.offset().left + g.dom.treeWidth
                    };
                },
                onDrag: function (current, e) {
                    var nodedata = this.draggingNode;
                    if (!nodedata)
                        return false;
                    var nodes = this.draggingNodes
							? this.draggingNodes
							: [nodedata];
                    if (g.nodeDropIn == null)
                        g.nodeDropIn = -1;
                    var pageX = e.pageX;
                    var pageY = e.pageY;
                    var visit = false;
                    var validRange = this.validRange;
                    if (pageX < validRange.left || pageX > validRange.right
							|| pageY > validRange.bottom
							|| pageY < validRange.top) {

                        g.nodeDropIn = -1;
                        g.nodeDroptip.hide();
                        this.proxy.find(".ux-drop-icon:first")
								.removeClass("ux-drop-yes ux-drop-add")
								.addClass("ux-drop-no");
                        return;
                    }
                    for (var i = 0, l = g.nodes.length; i < l; i++) {
                        var nd = g.nodes[i];
                        var treedataindex = nd['treedataindex'];
                        if (nodedata['treedataindex'] == treedataindex)
                            visit = true;
                        if ($.inArray(nd, nodes) != -1)
                            continue;
                        var isAfter = visit ? true : false;
                        if (g.nodeDropIn != -1 && g.nodeDropIn != treedataindex)
                            continue;
                        var jnode = $("li[treedataindex=" + treedataindex
										+ "] div:first", g.dom);
                        var offset = jnode.offset();
                        var range = {
                            top: offset.top,
                            bottom: offset.top + jnode.height(),
                            left: g.dom.offset().left,
                            right: g.dom.offset().left + g.dom.treeWidth
                        };
                        if (pageX > range.left && pageX < range.right
								&& pageY > range.top && pageY < range.bottom) {
                            var lineTop = offset.top;
                            if (isAfter)
                                lineTop += jnode.height();
                            g.nodeDroptip.css({
                                left: range.left,
                                top: lineTop,
                                width: range.right - range.left
                            }).show();
                            g.nodeDropIn = treedataindex;
                            g.nodeDropDir = isAfter ? "bottom" : "top";
                            if (pageY > range.top + 7
									&& pageY < range.bottom - 7) {
                                this.proxy.find(".ux-drop-icon:first")
										.removeClass("ux-drop-no ux-drop-yes")
										.addClass("ux-drop-add");
                                g.nodeDroptip.hide();
                                g.nodeDropInParent = true;
                            } else {
                                this.proxy.find(".ux-drop-icon:first")
										.removeClass("ux-drop-no ux-drop-add")
										.addClass("ux-drop-yes");
                                g.nodeDroptip.show();
                                g.nodeDropInParent = false;
                            }
                            break;
                        } else if (g.nodeDropIn != -1) {
                            g.nodeDropIn = -1;
                            g.nodeDropInParent = false;
                            g.nodeDroptip.hide();
                            this.proxy.find(".ux-drop-icon:first")
									.removeClass("ux-drop-yes  ux-drop-add")
									.addClass("ux-drop-no");
                        }
                    }
                },
                onStopDrag: function (current, e) {
                    var nodes = this.draggingNodes;
                    g.nodedragging = false;
                    if (g.nodeDropIn != -1) {
                        for (var i = 0; i < nodes.length; i++) {
                            var children = nodes[i].children;
                            if (children) {
                                nodes = $.grep(nodes, function (node, i) {
                                    var isIn = $.inArray(node, children) == -1;
                                    return isIn;
                                });
                            }
                        }
                        for (var i in nodes) {
                            var node = nodes[i];
                            if (g.nodeDropInParent) {
                                g.remove(node);
                                g.append(g.nodeDropIn, [node]);
                            } else {
                                g.remove(node);
                                g.append(g.getParent(g.nodeDropIn),
                                    [node], g.nodeDropIn,
                                    g.nodeDropDir == "bottom");
                            }
                        }
                        g.nodeDropIn = -1;
                    }
                    g.nodeDroptip.hide();
                    this.set('cursor', 'default');
                }
            });
        }
    },
    // 递归设置父节点的状态
    _setParentCheckboxStatus: function (treeitem) {
        var g = this;
        // 当前同级别或低级别的节点是否都选中了
        var isCheckedComplete = $(".ux-checkbox-unchecked", treeitem.parent()).length == 0;
        // 当前同级别或低级别的节点是否都没有选中
        var isCheckedNull = $(".ux-checkbox-checked", treeitem.parent()).length == 0;
        if (isCheckedComplete) {
            treeitem
					.parent()
					.prev()
					.find(".ux-checkbox")
					.removeClass("ux-checkbox-unchecked ux-checkbox-incomplete")
					.addClass("ux-checkbox-checked");
        } else if (isCheckedNull) {
            treeitem.parent().prev().find("> .ux-checkbox")
					.removeClass("ux-checkbox-checked ux-checkbox-incomplete")
					.addClass("ux-checkbox-unchecked");
        } else {
            treeitem.parent().prev().find("> .ux-checkbox")
					.removeClass("ux-checkbox-unchecked ux-checkbox-checked")
					.addClass("ux-checkbox-incomplete");
        }
        if (treeitem.parent().parent("li").length > 0)
            g._setParentCheckboxStatus(treeitem.parent().parent("li"));
    },
    filter: function (value, attr) {
        var g = this;
        if (value == "") {
            g.filterClear();
        } else {
            attr = attr || g.textFieldName;
            g.filterData = g.filterBy(g.data, attr, value);
            g.dom.html("");
            g.append(null, g.filterData);
        }
    },
    filterBy: function (nodes, key, value) {
        if (!nodes || !key) return [];
        var result = [];
        value = value.toLowerCase();
        for (var i = 0, l = nodes.length; i < l; i++) {
            if (typeof nodes[i][key] == "string" && nodes[i][key].toLowerCase().indexOf(value) > -1) {
                result.push(nodes[i]);
            } else {
                result = result.concat(this.filterBy(nodes[i]["children"], key, value));
            }
        }
        return result;
    },
    filterClear: function () {
        this.dom.html("");
        this.append(null, this.getData());
    }
});
﻿EIAP.MessageBox = function () {
    var win, opt, iconEl, msgEl, buttons;
    // private
    var handleButton = function (btn) {
        if (win) {
            win.close();
            if (opt.callback instanceof Function) {
                opt.callback.call(this, btn);
            }
        }
    };
    return {
        getWin: function () {
            var btns = [];
            buttons = {};
            for (var btn in opt.buttons) {
                buttons[btn] = {
                    title: this.buttonText[btn],
                    handler: handleButton.createCallback(btn)
                };
                btns.push(buttons[btn]);
            }
            win = EIAP.Window({
                title: opt.title || "&#160;",
                shadow: true,
                resizable: false,
                showClose: opt.showClose || true,
                showMax: false,
                showToggle: false,
                autoHeight: true,
                iconCls: opt.iconCls || "",
                buttonAlign: "center",
                width: opt.minWidth || this.minWidth,
                footer: true,
                buttons: btns
            });
            win.dom.addClass('ux-window-msg');
            iconEl = $('<div class="ux-mb-icon"></div>');
            if (opt.icon) {
                iconEl.addClass(opt.icon).show();
            }
            var contentEl = $('<div class="ux-mb-content"></div>');
            msgEl = $('<span class="ux-mb-text"></span>');
            contentEl.append(msgEl);
            win.dom.content.append(iconEl).append(contentEl).append('<div class="ux-clear"></div>');
            return win;
        },
        updateText: function (text) {
            msgEl.html(text || '&#160;');
            return this;
        },
        isVisible: function () {
            return win && win.dom.is(":visible");
        },
        hide: function () {
            if (this.isVisible()) {
                win.close();
            }
            return this;
        },
        show: function (options) {
            if (this.isVisible()) {
                this.hide();
            }
            opt = options;
            this.getWin(opt);
            this.updateText(opt.msg);
            win.shadow && win.dom.shadow.updateShadow(win.dom);
            return this;
        },
        OK: { ok: true },
        CANCEL: { cancel: true },
        OKCANCEL: { ok: true, cancel: true },
        YESNO: { yes: true, no: true },
        YESNOCANCEL: { yes: true, no: true, cancel: true },
        INFO: 'ux-mb-info',
        WARNING: 'ux-mb-warning',
        QUESTION: 'ux-mb-question',
        ERROR: 'ux-mb-error',
        maxWidth: 600,
        minWidth: 260,
        buttonText: {
            ok: "OK",
            cancel: "Cancel",
            yes: "Yes",
            no: "No"
        },
        alert: function (title, msg, handler) {
            this.show({
                title: title,
                msg: msg,
                buttons: this.OK,
                callback: handler,
                minWidth: this.minWidth
            });
            return this;
        },
        confirm: function (title, msg, handler) {
            this.show({
                title: title,
                msg: msg,
                buttons: this.YESNO,
                callback: handler,
                icon: this.QUESTION,
                minWidth: this.minWidth
            });
            return this;
        }
    };
} ();
EIAP.Msg = EIAP.MessageBox;﻿EIAP.ns("EIAP.tooltip");
EIAP.ToolTip = function () {
    return new EIAP.tooltip.ToolTip(arguments[0]);
};
EIAP.tooltip.iconType = {
    empty: '',
    error: 'icon-error',
    warning: 'icon-warning',
    succeed: 'icon-succeed'
};
EIAP.tooltip.ToolTip = EIAP.extend(EIAP.UIComponent, {
    top: 0,
    left: 0,
    title: null,
    tipText: null,
    arrowAlign: null,
    isInvalid: false,
    autoHide: true,
    width: 'auto',
    boxCss: 'ux-tooltip',
    toolBoxCss: "ux-header-toolbox",
    iconCss: "ux-tooltip-icon",
    innerCss: "ux-header-inner",
    contentCss: 'ux-tooltip-content',
    bwrapCss: 'ux-tooltip-bwrap',
    hearderCss: "ux-tooltip-header",
    invalidCss: "ux-invalid-tooltip",
    iconCls: null,
    isBubble: true,
    shadow: true,
    initComponent: function () {
        EIAP.tooltip.ToolTip.superclass.initComponent.call(this);
        if (this.isInvalid)
            this.iconCls = EIAP.tooltip.iconType.error;
    },
    __getType: function () {
        return 'ToolTip';
    },
    __idPrev: function () {
        return 'ToolTip';
    },
    _extMethods: function () {
        return EIAP.tooltip.ToolTip;
    },
    _render: function () {
        var g = this;
        g.dom = $("<div></div>");
        g.dom.addClass(g.boxCss);
        g.initContent();
        g.initHeader();
        g.addEvents();
        if (g.isBubble) {
            g.setBubble();
        }
        g.setWidth();
        g.isInvalid ? g.dom.addClass(g.invalidCss) : g.showShadow();
    },
    initContent: function () {
        var g = this;
        var content = $('<div class="' + g.contentCss + '"></div>');
        g.dom.empty();
        g.dom.append(content);
        g.dom.content = content;
        g.dom.content.bwrap = g.dom.content.wrap('<div class="' + g.bwrapCss + '"></div>').parent();
        g.dom.anchor = $('<div class="x-tooltip-anchor"></div>');
        if (g.arrowAlign) {
            g.dom.anchor.addClass('ux-tooltip-anchor-' + g.arrowAlign);
        }
        g.iconCls && g.dom.content.addClass("ux-tooltip-hasicon").addClass(g.iconCls);
        g.dom.append(g.dom.anchor);
        g.dom.appendTo('body');
    },
    initHeader: function () {
        var g = this;
        var header = $('<div class="' + g.hearderCss + '"></div>');
        var title = $('<div class="' + g.innerCss + '"></div>');
        if (g.title && !g.isInvalid) {
            header.toolbox = $('<div class="' + g.toolBoxCss + '"></div>');
            header.append(header.toolbox);
            title.html(g.title);
            header.append(title);
        }
        g.dom.title = title;
        g.dom.header = header;
        g.dom.prepend(g.dom.header);
    },
    addEvents: function () {
        var g = this;
        if (typeof g.target == "string") {
            g.target = $("#" + g.target);
        }
        g.target.bind("mouseover", function (e) {
            g.left = e.pageX || e.screenX;
            g.top = e.pageY || e.screenY;
            g.show();
        });
        if (g.autoHide) {
            g.target.bind("mouseout", function () {
                g.hide();
            });
        } else {
            g.dom.header.toolbox.append('<div class="ux-tool ux-window-tools ux-window-close"></div>');
            $(".ux-window-close", g.dom.header.toolbox).click(function () {
                g.hide();
            }).hover(function () {
                $(this).addClass("ux-window-close-over");
            }, function () {
                $(this).removeClass("ux-window-close-over");
            });
        }
    },
    showShadow: function () {
        var g = this;
        if (g.shadow && EIAP.Shadow) {
            g.dom.shadow = new EIAP.Shadow({ target: g.dom });
            g.items.push(g.dom.shadow.id);
        }
    },
    hide: function () {
        this.dom.css({
            "visibility": "hidden"
        });
        if (this.dom.shadow) this.dom.shadow.hide();
    },
    show: function () {
        var g = this;
        g.dom.css({
            "left": g.left + 10,
            "top": g.top + 5,
            "visibility": 'visible'
        });
        var tiptxt = g.tipText || g.target.attr("title") || "";
        g.target.attr("title", "");
        g.dom.content.html(tiptxt);
        g.shadow && g.dom.shadow && g.dom.shadow.updateShadow(g.dom);
    },
    close: function () {
        EIAP.remove(this);
    },
    setTipText: function () {
        var g = this;
        if (arguments.length > 0) {
            g.dom.content.html(arguments[0]);
        }
    },
    setWidth: function () {
        var g = this;
        if ($.browser.msie && parseFloat($.browser.version) <= 7) {
            g.dom.addClass("ux-tooltip-ie");
        }
        if (typeof g.width == "number") {
            g.dom.width(g.width);
        }
    },
    setBubble: function () {
        var g = this;
        var cls = g.type.toLowerCase();
        var tarr = ["tl", "tr", "tc"];
        var marr = ["ml", "mr", "mc"];
        var barr = ["bl", "br"];
        var head = g.dom.header;
        var body = g.dom.content;
        var bottom = $('<div class="ux-bc"></div>');
        if (g.bbar) {
            g.dom.content.bwrap.after(bottom);
        } else {
            g.dom.content.bwrap.append(bottom);
        }
        for (var i = 0; i < tarr.length; i++) {
            head = head.wrap('<div class="ux-' + tarr[i] + '"></div>');
        }
        for (i = 0; i < marr.length; i++) {
            body = body.wrap('<div class="ux-' + marr[i] + '"></div>');
        }
        for (i = 0; i < barr.length; i++) {
            bottom = bottom.wrap('<div class="ux-' + barr[i] + '"></div>');
        }
        g.dom.bottom = bottom.parent().parent();
        g.dom.bottom.addClass("ux-" + cls + "-nofooter");
    }
});﻿EIAP.ProcessStatus = function () {
    return new EIAP.tooltip.ProcessStatus(arguments[0]);
};
EIAP.ProcessStatus.statusType = {
    error: 'icon-error',
    warning: 'icon-warning',
    succeed: 'icon-succeed'
};
EIAP.tooltip.ProcessStatus = EIAP.extend(EIAP.tooltip.ToolTip, {
    width: 260,
    height: 65,
    postion: 'tc',
    status: false,
    title: '',
    showTime: 1500,
    msgDetail: '',
    iconCls: EIAP.ProcessStatus.statusType.succeed,
    autoHide: true,
    canClose: true,
    boxCss: 'ux-pstatus',
    toolBoxCss: "ux-header-toolbox",
    iconCss: "ux-tooltip-icon",
    innerCss: "ux-header-inner",
    contentCss: 'ux-pstatus-content',
    bwrapCss: 'ux-tooltip-bwrap',
    hearderCss: "ux-tooltip-header",
    initComponent: function () {
        EIAP.tooltip.ProcessStatus.superclass.initComponent.call(this);
    },
    __getType: function () {
        return 'ProcessStatus';
    },
    __idPrev: function () {
        return 'ProcessStatus';
    },
    _extMethods: function () {
        return EIAP.tooltip.ProcessStatus;
    },
    _render: function () {
        var g = this;
        g.initStatus();
        EIAP.tooltip.ProcessStatus.superclass._render.call(this);
        if (g.boxSkin) {
            g.dom.addClass(g.boxSkin);
        }
        g.show();
    },
    initContent: function () {
        var g = this;
        EIAP.tooltip.ProcessStatus.superclass.initContent.call(this);
        g.dom.content.removeClass("ux-tooltip-hasicon").removeClass(g.iconCls);
        if (g.height) {
            g.dom.content.height(g.height);
        }
    },
    initHeader: function () {
        var g = this;
        EIAP.tooltip.ProcessStatus.superclass.initHeader.call(this);
        if (g.iconCls) {
            var headerIcon = $('<div></div>');
            headerIcon.addClass("ux-panel-icon").addClass(g.iconCls);
            g.dom.title.prepend(headerIcon);
        }
    },
    addEvents: function () {
        var g = this;
        if (g.canClose) {
            g.dom.header.toolbox.append('<div class="ux-tool ux-window-tools ux-window-close"></div>');
            $(".ux-window-close", g.dom.header.toolbox).click(function () {
                g.hide();
            }).hover(function () {
                $(this).addClass("ux-window-close-over");
            }, function () {
                $(this).removeClass("ux-window-close-over");
            });
        }
    },
    hide: function () {
        var g = this;
        if (g.dom.shadow) g.dom.shadow.hide();
        g.dom.animate({ left: g.hideLeft, top: g.hideTop, opacity: '0' }, function () {
            EIAP.remove(g);
        });
    },
    show: function () {
        var g = this;
        g.setPosition();
        g.dom.css({
            "left": g.left,
            "top": g.top,
            "visibility": 'visible'
        });
        g.dom.content.html(g.msgDetail);
        g.dom.animate({ left: g.showLeft, top: g.showTop, opacity: '1' }, function () {
            g.shadow && g.dom.shadow && g.dom.shadow.updateShadow(g.dom);
        });
        if (g.autoHide || g.options.autoHide) {
            setTimeout(function () {
                g.hide();
            }, g.showTime);
        }
    },
    getStatus: function () {
        return this.result;
    },
    initStatus: function () {
        var g = this, status = g.status;
        g.result = false;
        if (status == false) return;
        if (status == null) {
            g.title = g.title || g.defaultTitle;
            g.msgDetail = g.defaultError;
            g.iconCls = EIAP.ProcessStatus.statusType.error;
            g.boxSkin = "ux-pstatus-error";
            g.autoHide = false;
        }
        else if (status.StatusSign == undefined) {
            g.title = g.title || g.defaultTitle;
            g.msgDetail = status;
            g.iconCls = EIAP.ProcessStatus.statusType.error;
            g.boxSkin = "ux-pstatus-error";
            g.autoHide = false;
        }
        else if (status.StatusSign == 0) {
            g.title = g.title || g.defaultTitle;
            g.msgDetail = status.Message;
            g.iconCls = EIAP.ProcessStatus.statusType.succeed;
            g.result = true;
        }
        else if (status.StatusSign == 1) {
            g.title = g.title || g.defaultTitle;
            g.msgDetail = status.Message;
            g.iconCls = EIAP.ProcessStatus.statusType.warning;
            g.boxSkin = "ux-pstatus-warning";
            g.autoHide = false;
        }
        else if (status.Message) {
            g.title = g.title || g.defaultTitle;
            g.msgDetail = status.Message;
            g.iconCls = EIAP.ProcessStatus.statusType.error;
            g.boxSkin = "ux-pstatus-error";
            g.autoHide = false;
        }
    },
    setPosition: function () {
        var g = this;
        switch (g.postion) {
            case 'tc':
                g.left = 0.5 * ($(window).width() - g.dom.width());
                g.top = g.hideTop = -100;
                g.showTop = 1;
                g.showLeft = g.hideLeft = g.left;
                break;
            case 'lt':
                g.left = g.hideLeft = -100;
                g.top = 0;
                g.showTop = g.hideTop = 1;
                g.showLeft = 2;
                break;
            case 'rt':
                g.left = $(window).width() - g.dom.width() - 4;
                g.top = g.hideTop = -100;
                g.showTop = 2;
                g.showLeft = g.hideLeft = g.left;
                break;
            case 'lb':
                g.left = -100;
                g.top = g.hideTop = $(window).height() - g.dom.height() - 4;
                g.showTop = g.top;
                g.showLeft = 2;
                g.hideLeft = -100;
                break;
            case 'rb':
                g.left = $(window).width() - g.dom.width() - 4;
                g.top = $(window).height() - g.dom.height() - 4;
                g.showTop = g.top;
                g.showLeft = g.left;
                g.hideLeft = g.left;
                g.hideTop = -100;
                break;
            case 'bc':
                g.left = 0.5 * ($(window).width() - g.dom.width());
                g.top = $(window).height() - g.dom.height() - 4;
                g.showTop = g.top;
                g.showLeft = g.left;
                g.hideLeft = g.left;
                g.hideTop = -100;
                break;
            default:
        }
    },
    onResize: function () {
        var g = this;
        g.setPosition();
        g.dom.css({
            "left": g.showLeft,
            "top": g.showTop,
            "visibility": 'visible'
        });
        g.shadow && g.dom.shadow && g.dom.shadow.updateShadow(g.dom);
    }
});﻿EIAP.WorkFlow = {
    showHistory: function (baseUrl, instanceId, title) {
        var g = this;
        if (EIAP.util.String.endsWith(baseUrl, "/")) {
            g.baseUrl = baseUrl;
        } else {
            g.baseUrl = baseUrl + "/";
        }
        var myMask = EIAP.LoadMask(null, { msg: EIAP.cmpText.loadingText });
        myMask.show();
        var url = g.baseUrl + g.showStatusMethod + "?callback=?";
        $.getJSON(url, { id: instanceId }, function (re) {
            myMask.hide();
            var wincfg = {
                title: title || EIAP.cmpText.flowStatus,
                iconCls: "icon-flow-transition",
                html: '',
                width: 700,
                height: 400,
                items: []
            };
            var waitbox = {
                xtype: "Panel",
                padding: 2,
                async: false,
                closable: false,
                html: '',
                title: g.tProcessStatus
            };
            var finishedbox = {
                xtype: "Panel",
                padding: 2,
                async: false,
                closable: false,
                html: '',
                title: g.tFlowHistory
            };
            var tabbox = {
                xtype: "TabPanel",
                padding: 0,
                border: false,
                items: []
            };
            var sbox = '<div style="height:45px;line-height:45px;border-bottom:1px solid #efefef;background-color:#FEFEFE;"><div style="height:22px;line-height:22px;padding-left:20px; background:url(resources/images/icons/common/spellcheck.png) no-repeat scroll 0 center transparent;"><span style="font-weight:bold;font-size:13px;color:#3897e3;">' + g.bFlowStart + '</span></div><div style="height:20px;line-height:20px;padding-left:25px;color:#686868;"><span style="font-size:12px;">' + re.Starter.UserName + '</span><span style="font-size:12px;padding-left:10px;">' + g.dateFormat(re.StarteTime, true) + '</span></div></div>';
            var bg = false;
            if (!re.IsCompleted) {
                var wbox = sbox, bgcls = "";
                for (var i = 0; i < re.ToDoWorkItems.length; i++) {
                    if (bg) {
                        bg = false;
                        bgcls = "background-color:#FEFEFE;";
                    } else {
                        bg = true;
                        bgcls = "";
                    }
                    wbox += '<div style="height:45px;line-height:45px;border-bottom:1px solid #efefef;' + bgcls + '"><div style="height:22px;line-height:22px;padding-left:20px;"><span style="font-weight:bold;font-size:13px;">【' + re.ToDoWorkItems[i].TaskName + '】</span></div><div style="height:20px;line-height:20px;padding-left:25px;color:#686868;">' + g.bWait + '(<span style="font-size:12px;font-weight:bold;">' + re.ToDoWorkItems[i].ExecutorUserName + '</span>)' + g.bTransact + '<span style="font-size:12px;padding-left:10px;">' + g.bTaskTime + g.dateFormat(re.ToDoWorkItems[i].CreateTime, true) + '</span></div></div>';
                }
                waitbox.html = wbox;
                tabbox.items.push(waitbox);
            }
            var cbox = sbox;
            bg = true;
            for (var k = 0; k < re.CompletedWorkItems.length; k++) {
                if (bg) {
                    bg = false;
                    bgcls = "";
                } else {
                    bg = true;
                    bgcls = "background-color:#FEFEFE;";
                }
                cbox += '<div style="height:45px;line-height:45px;border-bottom:1px solid #efefef;' + bgcls + '"><div style="height:22px;line-height:22px;padding-left:20px;"><span style="font-weight:bold;font-size:13px;">【' + re.CompletedWorkItems[k].TaskName + '】</span></div><div style="height:20px;line-height:20px;padding-left:25px;color:#686868;">' + g.bTransactor + '<span style="font-size:12px;">' + re.CompletedWorkItems[k].ExecutorUserName + '(' + g.dateFormat(re.CompletedWorkItems[k].ExecuteTime, true) + ')</span><span style="font-size:12px;padding-left:10px;">' + g.bTimeConsumed + re.CompletedWorkItems[k].TimeUsed + g.bTransactAbstract + re.CompletedWorkItems[k].ExecuteNote + '</span></div></div>';
            }
            if (re.IsCompleted) {
                if (bg) {
                    bgcls = "";
                } else {
                    bgcls = "background-color:#FEFEFE;";
                }
                var ebox = '<div style="height:45px;line-height:45px;border-bottom:1px solid #efefef;' + bgcls + '"><div style="height:22px;line-height:22px;padding-left:20px; background:url(resources/images/icons/common/spellcheckerror.png) no-repeat scroll 0 center transparent;"><span style="font-weight:bold;font-size:13px;color:#ff00ff;">' + g.bFlowEnd + '</span></div><div style="height:20px;line-height:20px;padding-left:25px;color:#686868;"><span style="font-size:12px;"></span><span style="font-size:11px;padding-left:10px;">' + g.dateFormat(re.CompletedTime, true) + '</span></div></div>';
                cbox += ebox;
            }
            finishedbox.html = cbox;
            tabbox.items.push(finishedbox);
            wincfg.items.push(tabbox);
            EIAP.Window(wincfg);
        });
    },
    dateFormat: function (time, istime) {
        if (time != null) {
            var date = new Date(parseInt(time.replace("/Date(", "").replace(")/", ""), 10));
            var month = date.getMonth() + 1 < 10 ? "0" + (date.getMonth() + 1) : date.getMonth() + 1;
            var currentDate = date.getDate() < 10 ? "0" + date.getDate() : date.getDate();
            if (istime) {
                var cH = date.getHours() < 10 ? "0" + date.getHours() : date.getHours();
                var cM = date.getMinutes() < 10 ? "0" + date.getMinutes() : date.getMinutes();
                var cS = date.getSeconds() < 10 ? "0" + date.getSeconds() : date.getSeconds();
                return date.getFullYear() + "-" + month + "-" + currentDate + " " + cH + ":" + cM + ":" + cS;
            }
            return date.getFullYear() + "-" + month + "-" + currentDate;
        }
        return "";
    },
    baseUrl: "",
    showStatusMethod: "OnWorkingHistory/GetWorkFlowInstanceState/",
    startMethod: "StartFlow/StartWorkFlow/",
    submitMethod: "StartFlow/WorkflowSubmit/",
    start: function (baseUrl, entityId, entityType, callBack, flowtypeid) {
        var g = this;
        if (!baseUrl || !entityId || !entityType)
            return;
        if (EIAP.util.String.endsWith(baseUrl, "/")) {
            g.baseUrl = baseUrl;
        } else {
            g.baseUrl = baseUrl + "/";
        }
        var myMask = EIAP.LoadMask(null, { msg: EIAP.cmpText.loadingFlow });
        myMask.show();
        var data = {
            entityId: entityId,
            businessEntityType: entityType,
            businessFlowTypeId: flowtypeid,
            r: new Date().getTime()
        };
        var url = g.baseUrl + g.startMethod + "?callback=?";
        g.frmItem = [], g.entityId = entityId;
        $.getJSON(url, data, function (re) {
            myMask.hide();
            if (re.AjaxResult.Sucessed) {
                if (re.BusinessFlowTypes != null) {
                    //todo
                    console.log("todo");
                } else {
                    var itembox = [];
                    g.flowVersionId = re.NextNodeInfo.BusinessFlowVersionId;
                    //开始【{0}({1})】
                    var title = String.format(g.tStart_1, re.NextNodeInfo.BusinessFlowName, re.NextNodeInfo.BusinessFlowCode);
                    var selectExecutors = re.NextNodeInfo.SelectExecutors;
                    var canSelectExecutors = re.NextNodeInfo.CanSelectExecutors;
                    var dType = re.NextNodeInfo.IsDynamicTaskNode ? "CheckBoxGroup" : "RadioBoxGroup";
                    var fieldarr, fieldvalue, userItems = [], h = "100%";
                    var nextNodes = re.NextNodeInfo.NextNodeTasks;
                    g.tagStatus.nextTasks = nextNodes;
                    if (selectExecutors.length == 0) {
                        if (nextNodes.length > 1)
                            h = 120;
                        for (var i = 0; i < nextNodes.length; i++) {
                            var task = nextNodes[i];
                            g.frmItem.push(task.Id);
                            var taskbox = { title: String.format(g.tSelectOperator, task.Name), iconCls: "icon-info-mail_recipient", defaultType: dType, defaultStyle: { labelWidth: 420 }, id: task.Id, height: h, items: [] };
                            for (var u = 0; u < canSelectExecutors.length; u++) {
                                var utask = canSelectExecutors[u];
                                if (utask.TaskId.toLowerCase() === task.Id.toLowerCase()) {
                                    fieldarr = ["TaskId", "ExecutorId", "ExecutorLogonName", "ExecutorUserName", "ExecutorLanguageCode", "ExecutorOrganizationName"];
                                    fieldvalue = { TaskId: task.Id, ExecutorId: utask.Executor.Id, ExecutorLogonName: utask.Executor.LogonName, ExecutorUserName: utask.Executor.UserName, ExecutorLanguageCode: utask.Executor.LanguageCode, ExecutorOrganizationName: utask.Executor.OrganizationName };
                                    if (re.NextNodeInfo.IsDynamicTaskNode) {
                                        userItems.push({ title: "<span style='color:#0000ff;'>" + utask.Executor.UserName + "</span> (" + utask.Executor.OrganizationName + ")", field: fieldarr, value: fieldvalue, labelFirst: false });
                                    } else {
                                        userItems.push({ title: "<span style='color:#0000ff;'>" + utask.Executor.UserName + "</span> (" + utask.Executor.OrganizationName + ")", field: fieldarr, value: fieldvalue, inputValue: utask.Executor.Id });
                                    }
                                }
                            }
                            if (userItems.length == 1) {
                                userItems[0].checked = true;
                            }
                            taskbox.items.push({ name: "Executors", defaultStyle: { labelWidth: 420 }, items: userItems });
                            itembox.push(taskbox);
                        }
                    } else {
                        var staskbox = { title: String.format(g.tSelectOperator, re.NextNodeInfo.NextNodeName), iconCls: "icon-info-mail_recipient", defaultType: dType, defaultStyle: { labelWidth: 420 }, id: re.NextNodeInfo.NextNodeId, height: h, items: [] };
                        g.frmItem.push(re.NextNodeInfo.NextNodeId);
                        fieldarr = ["TaskId", "ExecutorId", "ExecutorLogonName", "ExecutorUserName", "ExecutorLanguageCode", "ExecutorOrganizationName"];
                        for (var m = 0; m < selectExecutors.length; m++) {
                            var stask = selectExecutors[m];
                            fieldvalue = { TaskId: re.NextNodeInfo.NextNodeId, ExecutorId: stask.Id, ExecutorLogonName: stask.LogonName, ExecutorUserName: stask.UserName, ExecutorLanguageCode: stask.LanguageCode, ExecutorOrganizationName: stask.OrganizationName };
                            if (re.NextNodeInfo.IsDynamicTaskNode) {
                                userItems.push({ title: "<span style='color:#0000ff;'>" + stask.UserName + "</span> (" + stask.OrganizationName + ")", field: fieldarr, value: fieldvalue, labelFirst: false });
                            } else {
                                userItems.push({ title: "<span style='color:#0000ff;'>" + stask.UserName + "</span> (" + stask.OrganizationName + ")", field: fieldarr, value: fieldvalue, inputValue: stask.Id });
                            }
                        }
                        if (userItems.length == 1) {
                            userItems[0].checked = true;
                        }
                        staskbox.items.push({ name: "Executors", defaultStyle: { labelWidth: 420 }, items: userItems });
                        itembox.push(staskbox);
                        g.tagStatus.isSelect = true;
                    }
                    g.getStartFlowWin(title, itembox, callBack);
                }
            } else {
                EIAP.ProcessStatus({ status: re.AjaxResult });
            }
        });
    },
    getStartFlowWin: function (title, items, callBack) {
        var g = this;
        g.workFlowWin = EIAP.Window({
            title: EIAP.cmpText.startFlow + "—" + title,
            iconCls: "icon-flow-flow_start",
            width: 500,
            height: 260,
            defaultType: "FormPanel",
            items: items,
            buttonAlign: "center",
            buttons: [{
                title: EIAP.cmpText.ok,
                width: 50,
                iconCls: "icon-common-accept",
                handler: function () {
                    g.submitFlow(callBack);
                }
            }, {
                title: EIAP.cmpText.cancel,
                width: 50,
                iconCls: "icon-common-cross",
                handler: function () {
                    g.workFlowWin.close();
                }
            }]
        });
    },
    frmItem: [],
    flowVersionId: null,
    entityId: null,
    tagStatus: { isSelect: false, nextTasks: [] },
    setExecutors: function (frmuser) {
        var taskExecutor = {};
        taskExecutor.TaskId = frmuser.TaskId;
        taskExecutor.Executor = {
            Id: frmuser.ExecutorId,
            LogonName: frmuser.ExecutorLogonName,
            UserName: frmuser.ExecutorUserName,
            LanguageCode: frmuser.ExecutorLanguageCode,
            OrganizationName: frmuser.ExecutorOrganizationName
        };
        return taskExecutor;
    },
    getSubmitData: function () {
        var g = this, data = { succeed: true, message: "", flowModel: { EntityId: g.entityId, FlowVersionId: g.flowVersionId, TaskExecutors: [] } };
        if (g.frmItem.length == 0) {
            data.succeed = false, data.message = g.mFlowFailure;
        }
        for (var i = 0; i < g.frmItem.length; i++) {
            var frmcmp = EIAP.getCmp(g.frmItem[i]);
            var frmdata = frmcmp.getFormValue();
            if (frmdata.Executors instanceof Array) {
                var execs = frmdata.Executors;
                if (execs.length == 0) {
                    data.succeed = false, data.message = g.mFlowFailure_2 + frmcmp.title;
                } else {
                    for (var u = 0; u < execs.length; u++) {
                        data.flowModel.TaskExecutors.push(g.setExecutors(execs[u]));
                    }
                }
            } else if (frmdata.TaskId) {
                data.flowModel.TaskExecutors.push(g.setExecutors(frmdata));
            } else {
                data.succeed = false, data.message = g.mFlowFailure_2 + frmcmp.title;
            }
        }
        if (g.tagStatus.isSelect) {
            var tmpTaskExecutors = [], num = 0;
            for (var k = 0; k < g.tagStatus.nextTasks.length; k++) {
                var task = g.tagStatus.nextTasks[k];
                for (var m = 0; m < data.flowModel.TaskExecutors.length; m++) {
                    tmpTaskExecutors[num] = {};
                    tmpTaskExecutors[num].TaskId = task.Id;
                    tmpTaskExecutors[num].Executor = data.flowModel.TaskExecutors[m].Executor;
                    num++;
                }
            }
            data.flowModel.TaskExecutors = tmpTaskExecutors;
        }
        return data;
    },
    submitFlow: function (callBack) {
        var g = this;
        var data = g.getSubmitData();
        if (!data.succeed) {
            EIAP.ProcessStatus({ status: { StatusSign: 2, Message: data.message } });
        } else {
            var myMask = EIAP.LoadMask(g.workFlowWin, { msg: EIAP.cmpText.loadingText });
            myMask.show();
            EIAP.Store({
                url: g.baseUrl + g.submitMethod,
                dataType: "jsonp",
                cache: false,
                params: { model: EIAP.util.Json.stringify(data.flowModel) },
                success: function (status) {
                    myMask.hide();
                    var tmpstatus = { StatusSign: status.Sucessed ? 0 : 2, Message: status.Message };
                    var sts = EIAP.ProcessStatus({ status: tmpstatus }).getStatus();
                    if (sts) {
                        g.workFlowWin.close();
                        if (callBack instanceof Function) {
                            callBack();
                        }
                    }
                }
            });
        }
    }
};﻿EIAP.ns("EIAP.workflow");
EIAP.SelectExecutor = function () {
    return new EIAP.workflow.SelectExecutor(arguments[0]);
};
EIAP.workflow.SelectExecutor = EIAP.extend(EIAP.panel.Panel, {
    executorInfo: null,
    workItemId: null,
    isAgree: null,
    submitWhenEnd: true,
    resumeNote: null,
    padding: 0,
    url: "../GetNextExecutors/",
    iconCls: "icon-common-copy",
    initComponent: function () {
        var g = this;
        this.title = String.format(g.allotExecutor, this.executorInfo.NextNodeName);
        this.initTaskCmp();
        EIAP.workflow.SelectExecutor.superclass.initComponent.call(this);
    },
    __getType: function () {
        return 'SelectExecutor';
    },
    __idPrev: function () {
        return 'SelectExecutor';
    },
    _extMethods: function () {
        return EIAP.workflow.SelectExecutor;
    },
    _rendered: function () {
        this.scrolled = this.dom[0].clientWidth != this.dom[0].offsetWidth;
        EIAP.workflow.SelectExecutor.superclass._rendered.call(this);
    },
    initTaskCmp: function () {
        var g = this;
        g.options.items = [];
        if (g.executorInfo.HasSameExecutor) {
            g.options.items = [{
                xtype: "Panel",
                title: g.selExecutor,
                height: 0,
                border: true,
                padding: 8,
                iconCls: "icon-info-mail_recipient",
                items: g.initTaskCmpItems("00000000-0000-0000-0000-000000000000")
            }];
            return;
        }
        var length = g.executorInfo.Tasks.length;
        for (var i = 0; i < length; i++) {
            var task = g.executorInfo.Tasks[i];
            g.options.items.push({
                xtype: "Panel",
                collapsible: length > 1 ? true : false,
                title: length == 1 ? "" : String.format(g.selNextExecutor, task.Value),
                height: 0,
                padding: 8,
                hearderCss: i > 0 ? "ux-panel-header ux-workflow-bordertop" : "ux-panel-header",
                iconCls: length == 1 ? null : "icon-info-mail_recipient",
                items: g.initTaskCmpItems(task.Key),
                afterCollapse: function () {
                    g.afterCollapseOrExpand();
                },
                afterExpand: function () {
                    g.afterCollapseOrExpand();
                }
            });
        }
    },
    initTaskCmpItems: function (taskId) {
        var g = this, taskExecutors = g.executorInfo.Executors;
        var items = [], checked = g.executorInfo.DefaultSelectAll || g.checkIsSingleExecutor(taskId, taskExecutors);
        for (var i = 0; i < taskExecutors.length; i++) {
            if (!taskId || taskId == taskExecutors[i].TaskId) {
                var item = {
                    xtype: g.executorInfo.IsMultiSelect ? "CheckBox" : "RadioBox",
                    labelFirst: false,
                    labelWidth: 400,
                    title: String.format("{0}（{1}）", taskExecutors[i].Executor.UserName, taskExecutors[i].Executor.OrganizationName),
                    checked: checked,
                    taskExecutor: taskExecutors[i],
                    onChecked: function () {
                        if (!g.executorInfo.IsMultiSelect) {
                            g.restChecked(this);
                        }
                    }
                };
                items.push(item);
            }
        }
        return items;
    },
    checkIsSingleExecutor: function (taskId, taskExecutors) {
        if (!taskId && taskExecutors.length == 1) {
            return true;
        }
        var count = 0;
        for (var i = 0; i < taskExecutors.length; i++) {
            if (taskId == taskExecutors[i].TaskId) {
                count++;
                if (count > 1) {
                    return false;
                }
            }
        }
        return true;
    },
    restChecked: function (radiobox) {
        var taskPanelItems = EIAP.getCmp(radiobox.parentCmp).items;
        for (var i = 0; i < taskPanelItems.length; i++) {
            var itemId = taskPanelItems[i];
            if (itemId != radiobox.id) {
                var chkcmp = EIAP.getCmp(itemId);
                chkcmp.checked = false;
                chkcmp.dom.fieldicon.removeClass("checked");
            }
        }
    },
    getNextExecutorData: function () {
        var g = this, nextExecutorData = [];
        if (g.executorInfo.HasSameExecutor) {
            var nextExecutors = g.getItemData(EIAP.getCmp(g.items[0]).items);
            if (nextExecutors.length == 0) {
                g.msgAlert(g.notSelNextExecutor);
                return false;
            }
            for (var i = 0; i < g.executorInfo.Tasks.length; i++) {
                var taskId = g.executorInfo.Tasks[i].Key;
                for (var j = 0; j < nextExecutors.length; j++) {
                    var taskExecutor = EIAP.applyIf({}, nextExecutors[j]);
                    taskExecutor.TaskId = taskId;
                    nextExecutorData.push(taskExecutor);
                }
            }
        } else {
            var taskCmps = g.items;
            for (var i = 0; i < taskCmps.length; i++) {
                var taskCmp = EIAP.getCmp(taskCmps[i]);
                var taskExecutors = g.getItemData(taskCmp.items);
                if (taskExecutors.length == 0) {
                    g.msgAlert(String.format(g.alertTaskExecutor, taskCmp.title === "" ? g.executorInfo.NextNodeName : taskCmp.title));
                    return false;
                }
                nextExecutorData = nextExecutorData.concat(taskExecutors);
            }
        }
        return nextExecutorData;
    },
    msgAlert: function (msg) {
        var g = this;
        EIAP.Msg.show({
            title: g.promptMsg,
            msg: msg,
            buttons: EIAP.Msg.OK,
            iconCls: 'icon-app',
            icon: EIAP.Msg.INFO
        });
    },
    getItemData: function (items) {
        var data = [];
        for (var i = 0; i < items.length; i++) {
            var radioBox = EIAP.getCmp(items[i]);
            if (radioBox.getValue()) {
                data.push(radioBox.taskExecutor);
            }
        }
        return data;
    },
    isValid: function () {
        var g = this;
        if (g.executorInfo.HasSameExecutor) {
            var nextExecutors = g.getItemData(EIAP.getCmp(g.items[0]).items);
            if (nextExecutors.length == 0) {
                g.msgAlert("还没有选择下一步执行人！");
                return false;
            }
        } else {
            var taskCmps = g.items;
            for (var i = 0; i < taskCmps.length; i++) {
                var taskCmp = EIAP.getCmp(taskCmps[i]);
                var taskExecutors = g.getItemData(taskCmp.items);
                if (taskExecutors.length == 0) {
                    g.msgAlert(String.format(g.alertTaskExecutor, taskCmp.title === "" ? g.executorInfo.NextNodeName : taskCmp.title));
                    return false;
                }
            }
        }
        return true;
    },
    submit: function (callback, resumeNote) {
        var g = this;
        var nextExecutorData = g.getNextExecutorData();
        if (nextExecutorData == false) {
            return;
        }
        EIAP.Store({
            url: "../ResumeWorkflow/",
            params: {
                isAgree: g.isAgree,
                workItemId: g.workItemId,
                resumeNote: resumeNote || g.resumeNote,
                nextExecutors: EIAP.util.Json.stringify(nextExecutorData)
            },
            success: function (status) {
                if (status && status.StatusSign == 0) {
                    callback && callback.call(this, true, status);
                } else {
                    callback && callback.call(this, false);
                    EIAP.ProcessStatus({ status: status });
                }
            },
            failure: function (re) {
                callback && callback.call(this, false);
                var status = { StatusSign: 2, Message: re.responseText };
                EIAP.ProcessStatus({ status: status });
            }
        });
    },
    afterCollapseOrExpand: function () {
        if (!(this.scrolled && this.dom[0].clientWidth != this.dom[0].offsetWidth)) {
            EIAP.resize(this);
            this.scrolled = this.dom[0].clientWidth != this.dom[0].offsetWidth;
        }
    }
});﻿EIAP.ns("EIAP.workflow");
EIAP.StartFlow = function () {
    return new EIAP.workflow.StartFlow(arguments[0]);
};
EIAP.workflow.StartFlow = function () {
    EIAP.apply(this, arguments[0]);
    this.init();
};
EIAP.apply(EIAP.workflow.StartFlow.prototype, {
    url: "../GetStartInfo/",
    entityType: null,
    entityId: null,
    batEntityId: null,
    flowTypeId: null,
    width: 480,
    height: 320,
    selectHeight: 288,
    afterSubmit: null,
    afterCancel: null,
    flowVersionId: null,
    errorMsg: "",
    requestCount: 0,
    totalCount: 1,
    iconCls: "icon-flow-flow_start",
    init: function () {
        if (this.batEntityId) {
            this.entityId = this.batEntityId[0];
            this.totalCount = this.batEntityId.length;
        }
        this.getStartInfo();
    },
    setHeight: function (executorInfo) {
        if (executorInfo.Tasks.length == 1 && executorInfo.Executors.length < 7) {
            this.win.setHeight(this.height - 60);
            EIAP.getCmp(this.entityId + "_user").setHeight(this.selectHeight
							- 60);
        }
    },
    getStartInfo: function () {
        var g = this;
        var myMask = EIAP.LoadMask(null, {
            msg: g.startMsg
        });
        myMask.show();
        EIAP.Store({
            url: this.url,
            params: {
                entityType: this.entityType,
                entityId: this.entityId,
                flowTypeId: this.flowTypeId
            },
            success: function (re) {
                myMask.hide();
                if (re.ExecutorInfo.Status.StatusSign == 0) {
                    g.flowVersionId = re.BusinessFlowVersionId;
                    g.initCmp(re);
                } else {
                    EIAP.ProcessStatus({
                        status: re.ExecutorInfo.Status
                    });
                }
            },
            failure: function (re) {
                myMask.hide();
                var status = {
                    StatusSign: 2,
                    Message: re.responseText
                };
                EIAP.ProcessStatus({
                    status: status
                });
            }
        });
    },
    getFirstExecutors: function (flowTypeId) {
        var g = this;
        var myMask = EIAP.LoadMask(g.win, {
            msg: g.mLoadData
        });
        myMask.show();
        EIAP.Store({
            url: "../GetFirstExecutors/",
            params: {
                flowTypeId: flowTypeId,
                entityId: this.entityId
            },
            success: function (re) {
                myMask.hide();
                if (re.ExecutorInfo.Status.StatusSign == 0) {
                    g.flowVersionId = re.BusinessFlowVersionId;
                    g.genSelectUserCmp(re.ExecutorInfo);
                    g.setHeight(re.ExecutorInfo);
                } else {
                    EIAP.ProcessStatus({
                        status: re.Status
                    });
                }
            },
            failure: function (re) {
                myMask.hide();
                var status = {
                    StatusSign: 2,
                    Message: re.responseText
                };
                EIAP.ProcessStatus({
                    status: status
                });
            }
        });
    },
    initCmp: function (startInfo) {
        var g = this;
        this.win = EIAP.Window({
            title: this.title + "(" + startInfo.FlowName + "—"
                    + startInfo.FlowCode + ")",
            iconCls: this.iconCls,
            width: this.width,
            height: this.height,
            buttonAlign: "center",
            showClose: false,
            remove: function () {
                g.remove();
            },
            buttons: [{
                title: EIAP.cmpText.ok,
                width: 40,
                iconCls: "icon-common-ok",
                handler: function () {
                    g.submit();
                }
            }, {
                title: EIAP.cmpText.cancel,
                width: 40,
                iconCls: "icon-common-cross",
                handler: function () {
                    if (g.afterCancel && g.afterCancel instanceof Function) {
                        g.afterCancel();
                    }
                    g.win.close();
                }
            }],
            html: String.format(
                    "<div id='{0}'></div><div id='{1}'></div>",
                    g.entityId + "_type", g.entityId + "_user")
        });
        this.initFlowTypeCmp(startInfo.BusinessFlowTypes);
        this.genSelectUserCmp(startInfo.ExecutorInfo);
        this.setHeight(startInfo.ExecutorInfo);
    },
    initFlowTypeCmp: function (flowTypes) {
        var g = this, flowTypeName = flowTypes[0].Name, flowTypeId = flowTypes[0].Id;
        var flag = false;
        if (g.flowTypeId) {
            for (var i = 0; i < flowTypes.length; i++) {
                if (flowTypes[i].Id == g.flowTypeId) {
                    flowTypeName = flowTypes[i].Name;
                    flowTypeId = flowTypes[i].Id;
                    flag = true;
                }
            }
        }
        var flowTypeCmp = EIAP.Container({
            height: 30,
            renderTo: this.entityId + "_type",
            items: [{
                xtype: "ComboBox",
                title: g.tFlowType,
                name: "Name",
                field: ["Id"],
                canClear: false,
                readonly: flag,
                value: {
                    Name: flowTypeName,
                    Id: flowTypeId
                },
                data: flowTypes,
                afterSelect: function (data) {
                    if (data.value.Id != g.preFlowTypeId) {
                        g.getFirstExecutors(data.value.Id);
                        g.preFlowTypeId = data.value.Id;
                    }
                }
            }]
        });
        flowTypeCmp.dom.addClass("ux-workflow-borderbottom");
        this.preFlowTypeId = flowTypes[0].Id;
    },
    genSelectUserCmp: function (executorInfo) {
        var userCmp = EIAP.getCmp(this.entityId + "_user");
        if (userCmp) {
            EIAP.remove(userCmp);
            this.win.getDom().append("<div id='" + this.entityId
							+ "_user'></div>");
        }
        EIAP.SelectExecutor({
            renderTo: this.entityId + "_user",
            executorInfo: executorInfo,
            height: this.selectHeight
        });
    },
    submit: function () {
        var g = this;
        var selectExecutor = EIAP.getCmp(g.entityId + "_user");
        if (!selectExecutor.isValid()) {
            EIAP.Msg.show({
                title: g.tTips,
                msg: g.mSelectTransctor,
                buttons: EIAP.Msg.OK,
                iconCls: 'icon-app',
                icon: EIAP.Msg.INFO
            });
            return;
        }
        var myMask = EIAP.LoadMask(null, {
            msg: g.mUploadData
        });
        myMask.show();
        var params = {
            flowVersionId: this.flowVersionId,
            firstExecutors: EIAP.util.Json
                .stringify(selectExecutor
                    .getNextExecutorData())
        };
        if (g.batEntityId) {
            for (var i = 0; i < g.batEntityId.length; i++) {
                params.entityId = g.batEntityId[i];
                g.submitSingle(params, myMask);
            }
        } else {
            params.entityId = g.entityId;
            g.submitSingle(params, myMask);
        }

    },
    submitSingle: function (params, myMask) {
        var g = this;
        EIAP.Store({
            url: "../StartWorkflow/",
            params: params,
            success: function (status) {
                g.requestCount++;
                if (g.requestCount == g.totalCount) {
                    myMask.hide();
                    EIAP.ProcessStatus({
                        status: status
                    });
                    if (status.StatusSign == 0) {
                        g.win.close();
                        g.afterSubmit && g.afterSubmit();
                    }
                }
            },
            failure: function (re) {
                g.errorMsg += re.responseText + "<br>";
                g.requestCount++;
                if (g.requestCount == g.totalCount) {
                    myMask.hide();
                    var status = {
                        StatusSign: 2,
                        Message: g.errorMsg
                    };
                    EIAP.ProcessStatus({
                        status: status
                    });
                    g.win.close();
                    g.afterSubmit && g.afterSubmit();
                }
            }
        });
    },
    remove: function () {
        EIAP.remove(EIAP.getCmp(this.entityId + "_user"));
        EIAP.remove(EIAP.getCmp(this.entityId + "_type"));
    }
});﻿EIAP.ApproveExecutor = function () {
    return new EIAP.workflow.ApproveExecutor(arguments[0]);
};
EIAP.workflow.ApproveExecutor = function () {
    EIAP.apply(this, arguments[0]);
    this.getExecutorInfo();
};
EIAP.apply(EIAP.workflow.ApproveExecutor.prototype, {
    workItemId: null,
    resumeNote: null,
    isAgree: null,
    submitWhenEnd: true,
    url: "../GetNextExecutors/",
    width: 480,
    height: 350,
    afterSubmit: null,
    afterCancel: null,
    initHeight: function () {
        if (this.executorInfo.Tasks.length == 1 &&
            this.executorInfo.Executors.length < 7) {
            this.height -= 60;
        }
    },
    getExecutorInfo: function () {
        var g = this;
        var myMask = EIAP.LoadMask(g, { msg: g.loadingExecutor});
        myMask.show();
        EIAP.Store({
            url: this.url,
            params: {
                workItemId: this.workItemId,
                isAgree: this.isAgree,
                submitWhenEnd: this.submitWhenEnd,
                resumeNote: this.resumeNote
            },
            success: function (re) {
                myMask.hide();
                if (re.Status.StatusSign == 0) {
                    g.executorInfo = re;
                    if (re.NeedSelectUser) {
                        g.initHeight();
                        g.initCmp();
                    } else {
                        var status = { StatusSign: 0, Message: g.nextNodeMsg};
                        EIAP.ProcessStatus({ status: status });
                        g.afterSubmit && g.afterSubmit();
                    }
                } else {
                    EIAP.ProcessStatus({ status: re.Status });
                }
            }, failure: function (re) {
                myMask.hide();
                var status = { StatusSign: 2, Message: re.responseText };
                EIAP.ProcessStatus({ status: status });
            }
        });
    },
    initCmp: function () {
        var g = this;
        g.win = EIAP.Window({
            title: g.allocateExecutor,
            iconCls: this.iconCls,
            width: this.width,
            height: this.height,
            showClose: false,
            buttonAlign: "center",
            buttons: [{
                title: EIAP.cmpText.ok,
                width: 40,
                iconCls: "icon-common-ok",
                handler: function () {
                    var boxcmp = EIAP.getCmp(g.win.items[3]);
                    var boxcmpfirst = EIAP.getCmp(boxcmp.items[0]);
                    var boxcmpse = EIAP.getCmp(boxcmp.items[1]);
                    var noteStr = EIAP.getCmp(boxcmpse.items[0]).getValue();
                    if (noteStr != "") {
                        if (noteStr.length <= 200) {
                            if (boxcmpfirst.isValid()) {
                                var myMask = EIAP.LoadMask(g.win, { msg: g.submitingMsg});
                                myMask.show();
                                boxcmpfirst.submit(function(success, status) {
                                    myMask.hide();
                                    if (success) {
                                        EIAP.ProcessStatus({ status: status });
                                        g.win.close();
                                        g.afterSubmit && g.afterSubmit();
                                    }
                                }, noteStr);
                            }
                        } else {
                            EIAP.Msg.alert(g.promptMsg, g.limitLength);
                        }
                    } else {
                        EIAP.Msg.alert(g.promptMsg, g.instructions);
                    }
                }
            }, {
                title: EIAP.cmpText.cancel,
                width: 40,
                iconCls: "icon-common-cross",
                handler: function () {
                    if (g.afterCancel && g.afterCancel instanceof Function) {
                        g.afterCancel();
                    }
                    g.win.close();
                }
            }],
            items: [{
                xtype: "Container",
                layout: "border",
                padding: 0,
                items: [{
                    xtype: "SelectExecutor",
                    region: "center",
                    border: false,
                    resumeNote: g.resumeNote,
                    workItemId: g.workItemId,
                    executorInfo: g.executorInfo
                }, {
                    region: "south",
                    title: g.instructionLength,
                    height: 50,
                    isOverFlow: false,
                    border: false,
                    padding: 2,
                    items: [{
                        xtype: "TextField",
                        name: "ReasonNote",
                        value: g.resumeNote,
                        width: 455
                    }]
                }]
            }]
        });
    }
});﻿EIAP.ns("EIAP.workflow");
EIAP.ApproveWorkflow = function () {
    return new EIAP.workflow.ApproveWorkflow(arguments[0]);
};
EIAP.workflow.ApproveWorkflow = function () {
    EIAP.apply(this, arguments[0]);
    this.getApproveInfo();
};
EIAP.apply(EIAP.workflow.ApproveWorkflow.prototype, {
    workItemId: null,
    todoWorkUrl: "../GetProcessRefInfo/",
    executorUrl: "../GetNextExecutors/",
    resumeUrl: "../ResumeWorkflow/",
    isNeedAgree: true,
    requestNum: 3,
    defaultNote: null,
    afterClose: null,
    getApproveInfo: function () {
        var g = this;
        g.id = new Date().getTime();
        g.loadedCount = 0;
        var mask = EIAP.LoadMask(null, { msg: g.loadingMsg});
        mask.show();
        g.getProcessRefInfo(mask);
        if (g.isNeedAgree) {
            //获取同意的执行人
            g.getExecutors(true, mask);
            //获取不同意的执行人
            g.getExecutors(false, mask);
        } else {
            //获取下一步执行人
            g.requestNum = 2;
            g.getExecutors(null, mask);
        }
    },
    getProcessRefInfo: function (mask) {
        var g = this;
        EIAP.Store({
            url: g.todoWorkUrl,
            params: { workItemId: g.workItemId },
            success: function (data) {
                g.loadedCount++;
                g.flowData = data;
                if (g.loadedCount == g.requestNum) {
                    mask.hide();
                    g.initCmp();
                }
            }, failure: function (re) {
                mask.hide();
                var status = { StatusSign: 2, Message: re.responseText };
                EIAP.ProcessStatus({ status: status });
            }
        });
    },
    getExecutors: function (isAgree, mask) {
        var g = this;
        EIAP.Store({
            url: g.executorUrl,
            params: {
                workItemId: g.workItemId,
                isAgree: isAgree,
                submitWhenEnd: false
            },
            success: function (data) {
                if (data.Status.StatusSign == 0) {
                    g.loadedCount++;
                    if (g.isNeedAgree) {
                        if (isAgree) {
                            g.agreeExecutorData = data;
                        } else {
                            g.disAgreeExecutorData = data;
                        }
                    } else {
                        g.agreeExecutorData = data;
                    }
                    if (g.loadedCount == g.requestNum) {
                        mask.hide();
                        g.initCmp();
                    }
                } else {
                    mask.hide();
                    EIAP.ProcessStatus({ status: data.Status });
                }
            }, failure: function (re) {
                mask.hide();
                var status = { StatusSign: 2, Message: re.responseText };
                EIAP.ProcessStatus({ status: status });
            }
        });
    },
    initCmp: function () {
        var g = this;
        g.win = EIAP.Window({
            title: String.format(g.title, g.flowData.NodeName),
            iconCls: "icon-common-appedit",
            width: 880,
            height: 400,
            padding: 0,
            afterClose: this.afterClose,
            buttonAlign: "center",
            buttons: [{
                title: g.submitButton,
                width: 60,
                iconCls: "icon-common-ok",
                handler: function () {
                    g.submit();
                }
            }, {
                title: g.cancelButton,
                width: 60,
                iconCls: "icon-common-cross",
                handler: function () {
                    g.win.close();
                }
            }],
            items: [{
                xtype: "Panel",
                padding: 0,
                html: g.getWorkFlowInfoHtml()
            }],
            remove: function () {
                g.remove();
            }
        });
        g.initApproveCmp();
        g.showArgeeExcutorCmp();
    },
    getWorkFlowInfoHtml: function () {
        var html = "<div class='us-flow-infoBox'><div style='height:143px;'>";
        html += this.getBriefHtml();
        html += "<div class='ux-flow-cutoffLine'></div>";
        html += this.getHistoryHtml();
        html += "</div>";
        html += this.getApproveHtml();
        return html + "</div>";
    },
    getBriefHtml: function () {
        var g = this;
        var html = "<div class='ux-flow-brief'>";
        html += "<div class='ux-flow-title'>" + g.businessSummary + "</div><div class='ux-flow-iconl'></div><div class='ux-flow-briefItem-box'>";
        html += this.getBriefItemHtml(g.flowOriginator, this.flowData.StarterName + "【" + this.flowData.StartTime + "】");
        html += this.getBriefItemHtml(g.applyUnit, this.flowData.OrgName);
        html += this.getBriefItemHtml(g.jobDescription, this.flowData.WorkCaption);
        html += "</div></div>";
        return html;
    },
    getBriefItemHtml: function (label, infoStr) {
        var html = "";
        html += "<div class='ux-flow-briefItem'>";
        html += "<div class='ux-flow-userInfo'>" + label + "</div>";
        html += "<span>" + infoStr + "</span>";
        html += "</div>";
        return html;
    },
    getHistoryHtml: function () {
        var g = this;
        var html = "<div class='ux-flow-history'>";
        html += "<div class='ux-flow-title'>" + g.processInfo + "</div>";
        html += this.getHistoryItemHtml();
        html += "</div>";
        return html;
    },
    getHistoryItemHtml: function () {
        var g = this;
        var html = "", len = this.flowData.Histories.length;
        if (len == 0) {
            return "<div style='color: #9E9E9E;'>" + g.approvalHistory + "</div>";
        }
        var history = this.flowData.Histories[len - 1];
        html += "<div class='ux-flow-historyItem'>";
        html += "<div><span class='ux-flow-userInfo'>" + history.TaskName + "：</span><span>" + history.ExecuteTime + "</span></div>";
        html += "<div><span class='ux-flow-userInfo'>" + history.ExecutorName + "：</span><span>" + history.Note + "</span></div>";
        html += "</div>";
        return html;
    },
    getApproveHtml: function () {
        var g = this;
        var html = "<div class='ux-flow-approvebox'>";
        html += "<div class='ux-flow-approveTitle'>" + g.flowProcess + "</div>";
        html += "<div class='ux-flow-process'>";
        html += "<div id='opinion_" + this.id + "'></div><div id='resumeNote_" + this.id + "'></div></div>";
        html += "<div id='uxFlowArrow' class='ux-flow-arrow'></div>";
        html += "<div style='height:224px;overflow:auto;'><div class='ux-flow-excutore'>";
        html += "<div id='agreeExcutore_" + this.id + "' class='ux-flow-excutore'></div><div id='disAgreeExcutore_" + this.id + "' class='ux-flow-excutore'></div></div></div>";
        return html + "</div>";
    },
    initApproveCmp: function () {
        var g = this;
        EIAP.TextArea({
            renderTo: "resumeNote_" + g.id,
            title: "<span style='font-weight:bold; color: #707070;'>" + g.handleSuggest + "</span>",
            name: "resumeNote",
            width: 200,
            allowBlank: false,
            value: g.defaultNote || (g.isNeedAgree ? g.approveMsg : "")
        });
        if (g.isNeedAgree) {
            EIAP.RadioBoxGroup({
                renderTo: "opinion_" + g.id,
                title: "<span style='font-weight:bold; color: #707070;'>" + g.approveOrNot + "</span>",
                name: "isAgree",
                items: [{
                    title: g.approveMsg,
                    inputValue: "true",
                    name: "isAgree",
                    checked: true
                }, {
                    title: g.notApproveMsg,
                    name: "isAgree",
                    inputValue: "false"
                }],
                onChecked: function (value) {
                    var noteCmp = EIAP.getCmp("resumeNote_" + g.id);
                    var resumeNote = noteCmp.getValue();
                    if (value == "true") {
                        if (!resumeNote) {
                            noteCmp.setValue(g.approveMsg);
                        }
                        g.showArgeeExcutorCmp();
                    } else {
                        noteCmp.setValue("");
                        g.showDisArgeeExcutorCmp();
                    }
                }
            });
        }
    },
    showArgeeExcutorCmp: function () {
        var g = this;
        g.disAgreeExcutore && g.disAgreeExcutore.hide();
        if (!g.agreeExecutorData.NeedSelectUser) {
            $("#uxFlowArrow").hide();
            return;
        }
        $("#uxFlowArrow").show();
        if (g.agreeExecutor) {
            g.agreeExecutor.show();
        } else {
            g.agreeExecutor = EIAP.SelectExecutor({
                renderTo: "agreeExcutore_" + g.id,
                height: 0,
                width: 530,
                border: true,
                padding: 2,
                isAgree: g.isNeedAgree ? true : null,
                workItemId: g.workItemId,
                executorInfo: g.agreeExecutorData
            });
        }
    },
    showDisArgeeExcutorCmp: function () {
        var g = this;
        g.agreeExecutor && g.agreeExecutor.hide();

        if (!g.disAgreeExecutorData.NeedSelectUser) {
            $("#uxFlowArrow").hide();
            return;
        }
        $("#uxFlowArrow").show();
        if (g.disAgreeExcutore) {
            g.disAgreeExcutore.show();
        } else {
            g.disAgreeExcutore = EIAP.SelectExecutor({
                renderTo: "disAgreeExcutore_" + g.id,
                height: 0,
                border: true,
                padding: 2,
                width: 530,
                isAgree: g.isNeedAgree ? false : null,
                workItemId: g.workItemId,
                executorInfo: g.disAgreeExecutorData
            });
        }
    },
    submit: function () {
        var g = this;
        var isAgree = "true";
        if (g.isNeedAgree) {
            isAgree = EIAP.getCmp("opinion_" + g.id).getSubmitValue().isAgree[0].isAgree;
        }
        var resumeNote = EIAP.getCmp("resumeNote_" + g.id).getValue();
        if (!resumeNote) {
            EIAP.Msg.show({
                title: g.promptMsg,
                msg: g.processMsg,
                buttons: EIAP.Msg.OK,
                icon: EIAP.Msg.INFO
            });
            return;
        }
        if (isAgree == "true") {
            if (g.agreeExecutor && g.agreeExecutor.isValid()) {
                var mask = EIAP.LoadMask(g.win, { msg: g.waitSubmitMsg});
                mask.show();
                g.agreeExecutor.submit(function (isSuccess, status) {
                    mask.hide();
                    if (isSuccess) {
                        EIAP.ProcessStatus({ status: status });
                        g.win.close();
                    }
                }, resumeNote);
            } else if (!g.agreeExecutor) {
                g.submitWhenEnd(isAgree, resumeNote);
            }
        } else {
            if (g.disAgreeExcutore && g.disAgreeExcutore.isValid()) {
                var mask = EIAP.LoadMask(g.win, { msg: g.waitSubmitMsg });
                mask.show();
                g.disAgreeExcutore.submit(function (isSuccess, status) {
                    mask.hide();
                    if (isSuccess) {
                        EIAP.ProcessStatus({ status: status });
                        g.win.close();
                    }
                }, resumeNote);
            } else if (!g.disAgreeExcutore) {
                g.submitWhenEnd(isAgree, resumeNote);
            }
        }
    },
    submitWhenEnd: function (isAgree, resumeNote) {
        var g = this;
        var mask = EIAP.LoadMask(g.win, { msg: g.waitSubmitMsg });
        mask.show();
        EIAP.Store({
            url: "../ResumeWorkflow/",
            params: {
                workItemId: g.workItemId,
                resumeNote: resumeNote,
                isAgree: g.isNeedAgree ? isAgree : null
            },
            success: function (status) {
                mask.hide();
                if (status.StatusSign == 0) {
                    EIAP.ProcessStatus({ status: status });
                    g.win.close();
                } else {
                    EIAP.ProcessStatus({ status: status });
                }
            },
            failure: function (re) {
                mask.hide();
                var status = { StatusSign: 2, Message: re.responseText };
                EIAP.ProcessStatus({ status: status });
            }
        });
    },
    remove: function () {
        EIAP.remove("resumeNote_" + this.id);
        EIAP.remove("opinion_" + this.id);
        EIAP.remove("agreeExcutore_" + this.id);
        EIAP.remove("disAgreeExcutore_" + this.id);
    }
});﻿EIAP.WorkFlowHistory = function () {
    return new EIAP.workflow.WorkFlowHistory(arguments[0]);
};
EIAP.workflow.WorkFlowHistory = function () {
    EIAP.apply(this, arguments[0]);
    this.getHisoryInfo();
};
EIAP.apply(EIAP.workflow.WorkFlowHistory.prototype, {   
    iconCls: "icon-flow-flow_chart",
    url: "../GetWorkflowStatus/",
    instanceId: null,
    showFlowImgIndex: 1,
    getHisoryInfo: function () {
        var g = this;
        g.baseUrl = $('script[src*="eiap-all"]').attr("src").split("Sei")[0];
        var myMask = EIAP.LoadMask(null, { msg: g.mGetProcessInfo });
        myMask.show();
        EIAP.Store({
            url: this.url,
            params: {
                instanceId: this.instanceId
            },
            success: function (info) {
                myMask.hide();
                g.data = info;
                g.initCmp(info);
            }, failure: function (re) {
                myMask.hide();
                var status = { StatusSign: 2, Message: re.responseText };
                EIAP.ProcessStatus({ status: status });
            }
        });
    },
    initCmp: function (data) {
        var g = this;
        EIAP.Window({
            title: this.title + "(" + data.FlowName + "—" + data.FlowCode + ")",
            iconCls: this.iconCls,
            width: 560,
            height: 400,
            padding: 0,
            items: [{
                xtype: "TabPanel",
                border: false,
                items: this.getTabItems(data),
                onActive: function (index) {
                    if (index == g.showFlowImgIndex) {
                        window.open(g.baseUrl + "WFConfig/WorkFlow/ShowFlow/?InstanceId=" + g.instanceId, '_blank');
                    }
                }
            }]
        });
    },
    getTabItems: function (historyInfo) {
        var items = [];
        var g = this;
        if (historyInfo.CurrentTasks) {
            items.push({
                xtype: "Panel",
                title: g.tProcessStatus,
                async: false,
                padding: 0,
                iconCls: "icon-common-apptask",
                html: this.getCurrentHtml(historyInfo.CurrentTasks)
            });
            this.showFlowImgIndex = 2;
        }
        items.push({
            xtype: "Panel",
            title: g.tProcessHistory,
            async: false,
            padding: 0,
            iconCls: "icon-common-apptile",
            html: this.getHistoryHtml(historyInfo)
        });
        items.push({
            xtype: "Panel",
            title: g.tProcessMap,
            iconCls: "icon-flow-sitemapapplicationblue"
        });
        return items;
    },
    getCurrentHtml: function (currentTasks) {
        var html = '<div class="ux-flow-currentNodebox">';
        for (var i = 0; i < currentTasks.length; i++) {
            html += this.getCurrentNodeHtml(currentTasks[i]);
        }
        return html + '</div>';
    },
    getHistoryHtml: function (historyInfo) {
        var html = '<div class="ux-flow-nodebox">';
        html += this.getStartHtml(historyInfo);
        if (historyInfo.Histories) {
            for (var i = 0; i < historyInfo.Histories.length; i++) {
                html += this.getApproveNodeHtml(historyInfo.Histories[i]);
            }
        }
        if (historyInfo.EndTime) {
            html += this.getEndHtml(historyInfo);
        }
        return html + '</div>';
    },
    getStartHtml: function (historyInfo) {
        var html = "";
        html += '<div class="ux-flow-start"><div class="ux-flow-startTitle">';
        html += '<span class="ux-flow-starticon"></span><span style="font-weight: bold; font-size: 13px; color: #3897e3;">' + this.processStart + '</span>';
        html += '</div><div class="ux-flow-startinfo"><span style="font-size: 12px;">' + historyInfo.StarterName + '</span>';
        html += '<span style="font-size: 12px; padding-left: 10px;">' + historyInfo.StartTime + '</span></div></div>';
        return html;
    },
    getEndHtml: function (historyInfo) {
        var html = "";
        html += '<div class="ux-flow-end"><div class="ux-flow-endTitle">';
        html += '<span class="ux-flow-endicon"></span><span style="font-weight: bold; font-size: 13px; color: #FF8400;">' + this.processEnd + '</span>';
        html += '</div><div class="ux-flow-endinfo"><span style="font-size: 12px;">' + historyInfo.EnderName + '</span>';
        html += '<span style="font-size: 12px; padding-left: 10px;">' + historyInfo.EndTime + '</span></div></div>';
        return html;
    },
    getApproveNodeHtml: function (task) {
        var html = '<div class="ux-flow-node">';
        html += '<div class="ux-flow-taskTitle"><span>' + task.TaskName + '</span></div>';
        html += '<div class="ux-flow-taskinfo"><b></b><div class="ux-flow-textbox">';
        html += '<p><strong>'+this.disposer+'</strong>' + task.ExecutorName + '（' + task.ExecuteTime + '）</p>';
        html += '<p><strong>'+this.timeConsumed+'</strong>' + task.ElapsedTime + '</p>';
        html += '<p><strong>' + this.disposeSummary + '</strong>' + task.Note + '</p>';
        html += '</div></div></div>';
        return html;
    },
    getCurrentNodeHtml: function (task) {
        var html = '<div class="ux-flow-node">';
        html += '<div class="ux-flow-taskTitle"><span>' + task.TaskName + '</span></div>';
        html += '<div class="ux-flow-taskinfo"><div class="ux-flow-textbox">';
        if (this.data.Suspended) {
            html += '<p class="ux-flow-p">' + this.data.SuspendNote + '</p>';
        } else {
            html += '<p class="ux-flow-p"><strong>'+this.waitForDisposer+'</strong>' + task.ExecutorName + '</p>';
        }
        html += '<p><strong>'+this.taskTime +'</strong>' + task.ArrivedTime + '</p>';
        html += '</div></div></div>';
        return html;
    }

});﻿EIAP.ns("EIAP.file");
EIAP.UploadFile = function () {
    return new EIAP.file.UploadFile(arguments[0]);
};

EIAP.file.UploadFile = EIAP.extend(EIAP.window.Window, {
    showClose: false,
    width: 560,
    fileType: "*.*", //文件类型限制,暂未实现
    maxSize: "30MB", //最大单位为MB
    url: "../UploadDocument4SeiUi/",
    formUrl: "../UploadDocument4Html4/",
    uploadType: "create",
    queueFiles: null,
    afterComplete: null,
    afterAllComplete: null,
    initComponent: function () {
        this.formUrl += "?entityId=" + this.entityId + "&uploadType=" + this.uploadType;
        this.queueFiles = [];
        this.checkSupportHtml5();
        this.initUploadList();
        if (this.supportHtml5) {
            this.initHtml5FileDom();
        } else {
            this.initHtml4FileDom();
        }
        EIAP.file.UploadFile.superclass.initComponent.call(this);
    },
    __getType: function () {
        return 'UploadFile';
    },
    __idPrev: function () {
        return 'UploadFile';
    },
    _extMethods: function () {
        return EIAP.file.UploadFile;
    },
    checkSupportHtml5: function () {
        if (typeof (Worker) != "undefined") {
            this.supportHtml5 = true;
        }
        else {
            this.supportHtml5 = false;
        }
    },
    cols: function () {
        var g = this;
        var cols = [{
                name: "fileId",
                hidden: true
            }, {
                name: "Id",
                hidden: true
            }, {
                name: "FileStatus",
                hidden: true
            }, {
                name: "Uploader",
                hidden: true
            }, {
                name: "UploadTime",
                hidden: true
            }, {
                label: g.colsFileName,
                name: "FileName",
                index: "FileName",
                width: 180
            }, {
                label: g.colsFileSize,
                name: "FileSize",
                index: "FileSize",
                width: 90,
                hidden: !this.supportHtml5
            }, {
                label: g.colsProgress,
                name: "progress",
                index: "progress",
                align: "center",
                width: 160,
                hidden: !this.supportHtml5
            }, {
                label: g.colsStatus,
                name: "status",
                index: "status",
                width: 100
            }, {
                name: "successful",
                index: "successful",
                hidden: true
            }];
        return cols;
    },
    initUploadList: function () {
        this.options.items = [{
            xtype: "GridPanel",
            parentCmp: this.id,
            isDefined: true,
            showSearch: false,
            id: "upgrid" + this.id,
            bbar: this.initBbar(),
            gridCfg: {
                loadonce: true,
                hasPager: false,
                colModel: this.cols()
            }
        }];
    },
    _rendered: function () {
        EIAP.file.UploadFile.superclass._rendered.call(this);
        this.uploadList = EIAP.getCmp("upgrid" + this.id);
        this.input && this.input.trigger('click');
    },
    initBbar: function () {
        var g = this;
        return [{
            title: g.bbarAdd,
            iconCls: "icon-common-hospital",
            handler: function () {
                if (!g.supportHtml5) {
                    if (g.input.val()) {
                        var input = $("<input name='file' type='file'/>").bind("change", function (e) {
                            g.html4AfterSelectFile(e.target.value);
                        });
                        g.form.append(input);
                        g.input = input;
                    }
                }
                g.input && g.input.trigger('click');
            }
        }, {
            title: g.bbarDelete,
            iconCls: "icon-common-itemdel",
            handler: function () {
                var row = g.uploadList.getSelectRow();
                if (row && row.fileId) {
                    EIAP.Msg.confirm(g.promptMsg, g.delPromptMsg, function (flag) {
                        if (flag == 'yes') {
                            if (row.Id) {
                                g.deleteFile(row);
                            } else {
                                g.uploadList.grid.delRowData(row.fileId);
                                g.updateQueue(row.fileId);
                            }
                        }
                    });
                } else {
                    EIAP.Msg.show({
                        title: g.promptMsg,
                        msg: g.selDelMsg,
                        buttons: EIAP.Msg.OK,
                        iconCls: 'icon-app',
                        icon: EIAP.Msg.INFO
                    });
                }
            }
        }, {
            title: g.bbarClear,
            iconCls: "icon-system-setting",
            handler: function () {
                g.afterCloseWin && g.afterCloseWin(g.uploadList.getGridData());
                g.uploadList.setDataInGrid([]);
                if (!g.supportHtml5) {
                    for (var i = 0; i < g.queueFiles.length; i++) {
                        g.queueFiles[i].remove();
                    }
                } else {
                    g.input.val("");
                }
                g.queueFiles = [];
            }
        }, "->", {
            title: g.startUpload,
            iconCls: "icon-flow-transition",
            handler: function () {
                if (g.queueFiles.length > 0) {
                    if (g.supportHtml5) {
                        g.setToolbarDisable(true);
                        g.xhrUpload();
                    } else {
                        g.myMask = EIAP.LoadMask(g, { msg: g.uploadMsg});
                        g.myMask.show();
                        if (!g.input.val()) {
                            g.input.remove();
                        }
                        g.form.submit();
                    }
                } else {
                    EIAP.Msg.show({
                        title: g.promptMsg,
                        msg: g.nonUploadFile,
                        buttons: EIAP.Msg.OK,
                        iconCls: 'icon-app',
                        icon: EIAP.Msg.INFO
                    });
                }
            }
        }, {
            title: g.accomplish,
            iconCls: "icon-common-ok",
            handler: function () {
                if (g.queueFiles.length > 0) {
                    EIAP.Msg.confirm(g.promptMsg, g.accomplishMsg, function (flag) {
                        if (flag == 'yes') {
                            g.onCloseWin();
                            g.close();
                        }
                    });
                } else {
                    g.onCloseWin();
                    g.close();
                }
            }
        }];
    },
    initHtml5FileDom: function () {
        var g = this;
        var input = $('<input type="file" multiple="multiple" name="files" style="display: none">');
        $("body").append(input);
        input.bind("change", function (e) {
            g.afterSelectFile(e);
        });
        this.input = input;
    },
    initHtml4FileDom: function () {
        var g = this;
        var iframe = $("<iframe></iframe>").appendTo("body");
        var flag = true;
        iframe.bind("load", function () {
            var form = $("<form enctype='multipart/form-data' action='" + g.formUrl + "' method='post'></form>");
            form.get(0).encoding = 'multipart/form-data';
            var input = $("<input name='file' type='file'/>").bind("change", function (e) {
                g.html4AfterSelectFile(e.target.value);
            });
            form.append(input);
            g.input = input;
            g.form = form;
            iframe.contents().find("body").append(form);
            var msgDom = $(this).contents().find("pre");
            if (msgDom.length > 0) {
                g.myMask.hide();
                var dataStr = msgDom.html();
                if (dataStr) {
                    var data = EIAP.util.Json.parse(dataStr);
                    if (data instanceof Array) {
                        for (var i = 0; i < data.length; i++) {
                            data[i].successful = 1;
                        }
                        g.uploadList.setDataInGrid(data);
                        iframe.remove();
                        g.onCloseWin();
                        g.close();
                        msgDom.remove();
                    } else if (data.msg) {
                        var status = { StatusSign: 2, Message: data.msg };
                        EIAP.ProcessStatus({ status: status, width: 300 });
                        g.uploadList.setDataInGrid([]);
                        g.input.val("");
                    }
                    g.queueFiles = [];
                }
            } else {
                if (flag) {
                    flag = false;
                    g.input.trigger("click");
                }
            }
        });
        iframe.hide();
        this.iframe = iframe;
    },
    html4AfterSelectFile: function (filename) {
        var g = this;
        var files = this.uploadList.getGridData();
        for (var i = 0; i < files.length; i++) {
            if (files[i].FileName == filename) {
                var status = { StatusSign: 0, Message: String.format(g.selectFileMsg + "<br>", filename) };
                EIAP.ProcessStatus({ status: status, showTime: 2000, width: 300 });
                return;
            }
        }
        var data = {
            FileName: filename,
            status: g.waitUpload,
            fileId: new Date().getTime()
        };
        g.uploadList.grid.addRowData(data.fileId, data);
        g.input.timeflag = data.fileId;
        g.queueFiles.push(g.input);
    },
    afterSelectFile: function (e) {
        var g = this;
        var files = e.target.files || e.dataTransfer.files;
        var message = "";
        for (var i = 0 ; i < files.length; i++) {
            var file = files[i];
            if (g.isInUploadList(file)) {
                message += String.format(g.fileListMsg + "<br>", file.name);
                continue;
            }
            if (file.size == 0) {
                message += String.format(g.fileSizeMsg + "<br>", file.name, g.maxSize);
                continue;
            }
            if (!g.checkSize(file.size)) {
                message += String.format(g.fileSizeBigMsg + "<br>", file.name, g.maxSize);
                continue;
            }
            var data = {};
            data.fileId = file.name + file.lastModifiedDate.getTime();
            data.FileName = file.name;
            data.FileSize = g.formatFileSize(file.size);
            data.progress = "<div class='ux-file-lodingbox'><div class='ux-file-progressbar' progress='" + data.fileId + "'></div></div>";
            data.status = g.waitUpload;
            var grid = g.uploadList.grid;
            grid.addRowData(data.fileId, data);
            g.queueFiles.push(file);
        };
        if (message) {
            var status = { StatusSign: 0, Message: message };
            EIAP.ProcessStatus({ status: status, showTime: 4000, width: 300 });
        }
        g.input.val("");
    },
    isInUploadList: function (file) {
        var files = this.uploadList.getGridData();
        for (var i = 0; i < files.length; i++) {
            if (files[i].FileName == file.name && files[i].fileId == file.name + file.lastModifiedDate.getTime()) {
                return true;
            }
        }
        return false;
    },
    checkSize: function (size) {
        var g = this;
        var len = this.maxSize.length;
        var sizeUnit = this.maxSize.toUpperCase().substring(len - 2, len);
        var sizeLimit = parseInt(g.maxSize);
        switch (sizeUnit) {
            case "MB":
                sizeLimit = sizeLimit * 1024 * 1024;
                break;
            case "KB":
                sizeLimit = sizeLimit * 1024;
                break;
            default:
                break;
        }
        return size <= sizeLimit;
    },
    formatFileSize: function (size) {
        if (size > 1024 * 1024) {
            size = (Math.round(size * 100 / (1024 * 1024)) / 100).toString() + 'MB';
            if (size > 30) {
                return false;
            }
        }
        else {
            size = (Math.round(size * 100 / 1024) / 100).toString() + 'KB';
        }
        return size;
    },
    xhrUpload: function () {
        var g = this;
        for (var i = 0; i < g.queueFiles.length; i++) {
            var tmpFile = g.queueFiles[i];
            (function (file) {
                var xhr = new XMLHttpRequest();
                if (xhr.upload) {
                    // 上传中
                    xhr.upload.addEventListener("progress", function (e) {
                        g.onProgress(file, e.loaded, e.total);
                    }, true);

                    // 文件上传成功或是失败
                    xhr.onreadystatechange = function () {
                        if (xhr.readyState == 3) {
                            try {
                                var result = eval('(' + xhr.responseText + ')');
                                if (!result.Id) {
                                    xhr.abort();
                                    g.onFailure(file);
                                }
                            } catch (e) {
                                xhr.abort();
                                g.onFailure(file);
                            }
                        }
                        if (xhr.readyState == 4) {
                            if (xhr.status == 200) {
                                var response = eval('(' + xhr.responseText + ')');
                                g.onSuccess(file, response);
                                g.updateQueue(file.name + file.lastModifiedDate.getTime());
                                if (!g.queueFiles.length) {
                                    //全部完毕
                                    g.onAllComplete();
                                }
                            } else {
                                g.onFailure(file);
                            }
                        }
                    };
                    var url = g.url + "?entityId=" + g.entityId + "&uploadType=" + g.uploadType;
                    // 开始上传
                    xhr.open("POST", url, true);
                    xhr.setRequestHeader("x-charset", "utf-8");
                    xhr.setRequestHeader("Accept-Language", "zh-cn,zh;q=0.8,en-us;q=0.5,en;q=0.3");
                    xhr.setRequestHeader("Content-Type", "multipart/form-data");
                    xhr.setRequestHeader("X_FILENAME", escape(file.name));
                    xhr.send(file);
                }
            })(tmpFile);
        }
    },
    formUpload: function () {
        this.form.submit();
    },
    onProgress: function (file, complete) {
        this.updateProgress(file, complete);
    },
    onSuccess: function (file, fileData) {
        this.updateProgress(file, file.size);
        var fileId = file.name + file.lastModifiedDate.getTime();
        var grid = this.uploadList.grid;
        grid.setRowData(fileId, {
            Id: fileData.Id, FileType: fileData.FileType, FileStatus: fileData.FileStatus,
            Uploader: fileData.Uploader, UploadTime: fileData.UploadTime, successful: 1
        });
        this.afterComplete && this.afterComplete();
    },
    onFailure: function (file) {
        var fileId = file.name + file.lastModifiedDate.getTime();
        this.updateQueue(fileId);
        $("div[progress='" + fileId + "']", this.dom).remove("ux-file-progressbar").addClass("ux-file-brokenprogressbar").attr("style", "");
        var grid = this.uploadList.grid;
        grid.setRowData(fileId, { status: g.uploadFailure});
        if (!this.queueFiles.length) {
            //全部完毕
            this.onAllComplete();
        }
    },
    onAllComplete: function () {
        this.setToolbarDisable(false);
    },
    onCloseWin: function () {
        if (this.afterCloseWin) {
            this.afterCloseWin(this.uploadList.getGridData());
        }
    },
    updateProgress: function (file, complete) {
        var fileId = file.name + file.lastModifiedDate.getTime();
        var total = file.size;
        var progress = $("div[progress='" + fileId + "']", this.dom);
        var totalWidth = progress.parent().width();
        var width = parseInt(totalWidth * complete / total);
        progress.css({ width: width });
        var grid = this.uploadList.grid;
        grid.setRowData(fileId, { status: parseInt(100 * complete / total) + "%" });
    },
    updateQueue: function (fileId) {
        var g = this;
        if (g.supportHtml5) {
            for (var i in g.queueFiles) {
                var file = g.queueFiles[i];
                if (fileId == file.name + file.lastModifiedDate.getTime()) {
                    g.queueFiles.splice(i, 1);
                    break;
                }
            }
        } else {
            for (var i = 0 ; i < g.queueFiles.length; i++) {
                if (fileId == g.queueFiles[i].timeflag.toString()) {
                    g.queueFiles[i].remove();
                    g.queueFiles.splice(i, 1);
                    break;
                }
            }
        }
    },

    deleteFile: function (row) {
        var g = this;
        var myMask = EIAP.LoadMask(g, { msg: g.deletingMsg});
        myMask.show();
        $.ajax({
            type: "post",
            url: "../DeletDocument/",
            data: { fileGuid: row.Id },
            success: function (response) {
                myMask.hide();
                if (response == "successfully!") {
                    var status = { StatusSign: 0, Message: g.deletingSuccess};
                    EIAP.ProcessStatus({ status: status });
                    g.uploadList.grid.delRowData(row.fileId);
                    g.updateQueue(row.fileId);
                }
            },
            failure: function (re) {
                myMask.hide();
                var status = { StatusSign: 2, Message: re.responseText };
                EIAP.ProcessStatus({ status: status });
            }
        });
    },
    setToolbarDisable: function (disable) {
        var buttons = EIAP.getCmp(this.uploadList.bbar).items;
        for (var i = 0; i < buttons.length; i++) {
            if (disable) {
                EIAP.getCmp(buttons[i]).disable();
            } else {
                EIAP.getCmp(buttons[i]).enable();
            }
        }
    },
    setEntityId: function (entityId) {
        this.entityId = entityId;
        this.UploadFile.setEntityId(entityId);
    },
    setUploadType: function (uploadType) {
        this.uploadType = uploadType;
    },
    remove: function () {
        this.input.remove();
        EIAP.file.UploadFile.superclass._rendered.call(this);
    }
});﻿EIAP.ns("EIAP.file");
EIAP.UploadList = function () {
    return new EIAP.file.UploadList(arguments[0]);
};
EIAP.file.UploadList = EIAP.extend(EIAP.grid.GridPanel, {
    url: "../GetDocumentsList4SeiUi/",
    downloadUrl: "../DownLoadDocument/",
    data: null,
    submitUrl: "../SubmitEntityDocument/",
    entityId: null,
    display: false,
    canRef: false,
    uploadType: "create",
    afterDataChange: null,
    initComponent: function () {
        this.getGridCfg();
        this.initTbar();
        EIAP.file.UploadList.superclass.initComponent.call(this);
    },
    __getType: function () {
        return 'UploadList';
    },

    __idPrev: function () {
        return 'UploadList';
    },

    _extMethods: function () {
        return EIAP.file.UploadList;
    },
    getGridCfg: function () {
        var g = this;
        g.gridCfg = g.gridCfg || {};
        var cols = [{ name: "Id", index: "Id", hidden: true },
            { name: "IsForbidDelete", index: "IsForbidDelete", hidden: true },
            { name: "FileType", index: "FileType", hidden: true },
            { label: g.filesName, name: "FileName", index: "FileName", width: 260 },
            { label: g.fileSize, name: "FileSize", index: "FileSize", width: 70 },
            { label: g.uploadPerson, name: "Uploader", index: "Uploader", width: 90 },
            { label: g.uploadTime, name: "UploadTime", index: "UploadTime", width: 120 },
            { label: g.fileStatus, name: "FileStatus", index: "FileStatus", width: 110, hidden: true }
        ];
        if (g.canRef) {
            cols.splice(4, 0, { label: g.fileRemark, name: "Remark", index: "Remark", width: 190 });
        }
        EIAP.apply(g.gridCfg, {
            url: g.data ? null : g.url,
            postData: {
                entityId: g.entityId
            },
            loadonce: true,
            hasPager: false,
            shrinkToFit: false,
            rowNum: 1000,
            localReader: { id: "Id" },
            sortname: 'UploadTime',
            colModel: cols
        });
        if (g.data instanceof Array) {
            g.gridCfg.data = g.data;
        }
    },
    initTbar: function () {
        var g = this;
        var download = {
            title: g.downloadMsg,
            iconCls: "icon-common-download",
            handler: function () {
                var row = g.getSelectRow();
                if (row.Id) {
                    g.downloadFile(row.Id);
                } else {
                    EIAP.Msg.show({
                        title: g.promptMsg,
                        msg: g.selectAttachment,
                        buttons: EIAP.Msg.OK,
                        iconCls: 'icon-app',
                        icon: EIAP.Msg.INFO
                    });
                }
            }
        };
        if (g.display) {
            g.tbar = [download];
            return;
        }
        g.tbar = [{
            title: g.addAttachment,
            iconCls: "icon-common-attachment",
            handler: function () {
                if (!g.entityId) return false;
                g.UploadFile = EIAP.UploadFile({
                    entityId: g.entityId,
                    uploadType: g.uploadType,
                    afterCloseWin: function (files) {
                        for (var i = 0; i < files.length; i++) {
                            var file = files[i];
                            if (file.successful == 1) {
                                g.grid.addRowData(file.Id, file);
                            }
                        }
                        if (files.length) {
                            g.afterDataChange && g.afterDataChange(g.getGridData());
                        }
                    }
                });
            }
        }, {
            title: g.deleteMsg,
            iconCls: "icon-common-itemdel",
            handler: function () {
                var row = g.getSelectRow();
                if (row.Id) {
                    if (row.IsForbidDelete.toLocaleLowerCase() === "true") {
                        EIAP.Msg.show({
                            title: g.promptMsg,
                            msg: g.deleteFailMsg,
                            buttons: EIAP.Msg.OK,
                            iconCls: 'icon-app',
                            icon: EIAP.Msg.ERROR
                        });
                    } else {
                        EIAP.Msg.confirm(g.promptMsg, g.confirmDelMsg, function (flag) {
                            if (flag == 'yes') {
                                g.deleteFile(row.Id);
                            }
                        });
                    }
                } else {
                    EIAP.Msg.show({
                        title: g.promptMsg,
                        msg: g.selectDelMsg,
                        buttons: EIAP.Msg.OK,
                        iconCls: 'icon-app',
                        icon: EIAP.Msg.INFO
                    });
                }
            }
        }, download];
        if (g.canRef) {
            g.tbar.push({
                title: g.referenceMsg,
                iconCls: "icon-common-boxshare",
                handler: function () {
                    if (EIAP.UserGather) {
                        g.userGather = EIAP.UserGather({
                            amCmp: g,
                            entityId: g.entityId,
                            startTime: EIAP.util.Date.fn.getDay(-30),
                            endTime: EIAP.util.Date.fn.getDay()
                        });
                    } else {
                        throw new Error(String.format(EIAP.error.noCmp, "EIAP.UserGather"));
                    }
                }
            });
        }
    },
    deleteFile: function (fileGuid) {
        var g = this;
        var myMask = EIAP.LoadMask(g, { msg: g.deletingMsg});
        myMask.show();
        $.ajax({
            type: "post",
            url: "../DeletDocument/",
            data: { fileGuid: fileGuid },
            success: function (response) {
                myMask.hide();
                if (response == "successfully!") {
                    var status = { StatusSign: 0, Message: g.deletedSuccess};
                    EIAP.ProcessStatus({ status: status });
                    g.grid.delRowData(fileGuid);
                    g.afterDataChange && g.afterDataChange(g.getGridData());
                }
            },
            failure: function (re) {
                myMask.hide();
                var status = { StatusSign: 2, Message: re.responseText };
                EIAP.ProcessStatus({ status: status });
            }
        });
    },
    downloadFile: function (fileGuid) {
        var g = this;
        if (!g.downloadFrame) {
            var iframe = $("<iframe></iframe>").css("display", "none");;
            $("body").append(iframe);
            g.downloadFrame = iframe;
        }
        g.downloadFrame.attr("src", g.downloadUrl + "?fileGuid=" + fileGuid);
    },
    setEntityId: function (entityId) {
        this.entityId = entityId;
        this.UploadFile && this.UploadFile.setEntityId(entityId);
    },
    setUploadType: function (uploadType) {
        this.UploadFile && this.UploadFile.setUploadType(uploadType);
    },
    remove: function () {
        this.UploadFile && EIAP.remove(this.UploadFile);
        this.downloadFrame && this.downloadFrame.remove();
    },
    submit: function (config) {
        var g = this;
        var store = {
            url: this.submitUrl,
            params: {
                entityId: this.entityId
            },
            failure: function (response) {
                if (response == "successfully!" && config.success) {
                    var status = { StatusSign: 0, Message: g.saveAttachment};
                    config.success.call(this, status);
                } else {
                    var status = { StatusSign: 2, Message: response };
                    config.failure.call(this, status);
                }
            }
        };
        EIAP.applyIf(store, config);
        EIAP.Store(store);
    }
});﻿EIAP.BatchImport = function () {
    var instance = new EIAP.file.BatchImport(arguments[0]);
    window[instance.timestamp] = instance;
    return instance;
};
EIAP.file.BatchImport = function () {
    EIAP.apply(this, arguments[0]);
    this.initComponent();
};
EIAP.apply(EIAP.file.BatchImport.prototype, {
    url: "",
    params: null,
    templateUrl: "",
    width: 500,
    height: 300,
    beforeClose: null,
    confirm: null,
    afterLoad: null,
    timestamp: "timestamp_" + new Date().getTime(),
    initComponent: function () {
        var g = this;
        g.win = EIAP.Window({
            title: g.title,
            width: g.width,
            height: g.height,
            buttonAlign: "center",
            buttons: g.initToolBar(),
            items: [{
                xtype: "GridPanel",
                tbar: g.initGridBar(),
                showSearch: false,
                gridCfg: g.gridCfg
            }],
            afterClose: function () {
                g.remove();
            }
        });
        g.gridList = EIAP.getCmp(g.win.items[3]);
        g.initUrl();
        g.initUploadDom();
    },
    initUrl: function () {
        var g = this;
        if (!g.params) {
            return;
        }
        var flag = false;
        for (var key in g.params) {
            if (flag) {
                g.url += "&" + key + "=" + g.params[key];
            } else {
                g.url += "?" + key + "=" + g.params[key];
                flag = true;
            }
        }
    },
    initUploadDom: function () {
        var g = this;
        var iframe = $("<iframe style='display:none;'></iframe>");
        iframe.appendTo("body");
        g.mask = EIAP.LoadMask(g.win, { msg: g.initUploadMsg });
        //兼容谷歌浏览器
        if ($.browser.webkit) {
            iframe.attr("src", "#");
        }
        iframe.bind("load", function () {
            var form = $("<form enctype='multipart/form-data' action='" + g.url + "' method='post'><input name='timestamp' type='text' value='" + g.timestamp + "'/></form>");
            g.input = $("<input name='file' type='file'/>").bind("change", function () {
                g.mask.show();
                form.submit();
            });
            form.append(g.input);
            iframe.contents().find("body").append(form);
            g.iframe = iframe;
        });
    },
    getResponse: function (data) {
        this.mask.hide();
        this.afterLoad && this.afterLoad(data);
    },
    initToolBar: function () {
        var g = this;
        return [{
            title: g.toolBarConfirm,
            width: 50,
            iconCls: "icon-common-ok",
            handler: function () {
                if (g.confirm) {
                    var data = g.gridList.getGridData();
                    var result = g.confirm(data);
                    if (result == false) {
                        return;
                    }
                }
                g.win.close();
            }
        }, {
            title: g.toolBarCancel,
            width: 50,
            iconCls: "icon-common-cross",
            handler: function () {
                g.win.close();
            }
        }];
    },
    initGridBar: function () {
        var g = this;
        var bar = [{
            title: g.gridBarSelect,
            iconCls: "icon-common-hospital",
            handler: function () {
                g.iframe.contents().find("input").click();
            }
        }, {
            title: g.gridBarDelete,
            iconCls: "icon-common-dele_red",
            handler: function () {
                var row = g.gridList.getSelectRow();
                if (row.Id) {
                    EIAP.Msg.confirm(g.gridDeletePrompt, g.gridDelPromptMsg, function (flag) {
                        if (flag == 'yes') {
                            g.gridList.grid.delRowData(row.Id);
                        }
                    });
                } else {
                    EIAP.Msg.show({
                        title: g.gridDeletePrompt,
                        msg: g.gridSelDelMsg,
                        buttons: EIAP.Msg.OK,
                        iconCls: 'icon-app',
                        icon: EIAP.Msg.INFO
                    });
                }
            }
        }];
        if (g.templateUrl) {
            bar.push("->");
            bar.push({
                title: g.templateDownload,
                iconCls: "icon-common-download",
                handler: function () {
                    window.location.href = g.templateUrl;
                }
            });
        }
        return bar;
    },
    remove: function () {
        this.iframe.remove();
    }
});